How to find the ip address of google.com using dig

I know I can do dig google.com and it will display lots of information including Google.com IP address

; <> DiG 9.16.1-Ubuntu <> google.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 36992
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;google.com.			IN	A

;; ANSWER SECTION:
google.com.		32	IN	A	172.217.2.238

;; Query time: 0 msec
;; SERVER: 127.0.0.53#53(127.0.0.53)
;; WHEN: Fri Jan 08 20:21:38 UTC 2021
;; MSG SIZE  rcvd: 55


But how do I just get IP address of Google.com using dig? Like I need 172.217.2.238 and store in a shell variable. Something as follows

google_com_ip="172.217.2.238"

I don’t know how to do that as I can’t grep it. Can you provide help?

Pass the +short option to dig command on Linux or Unix:

Provide a terse answer. The default is to print the answer in a verbose form. This option always has a global effect; it cannot be set globally and then overridden on a per-lookup basis.

Example

dig +short google.com

Same as above:

dig +short A google.com

Get IPv6:

dig +short AAAA google.com

Want to stroe that (google or any other dns) IPv4 address to a shell variable? No problem:

google_com_ip="$(dig +short A google.com)"
echo "$google_com_ip"

Host command can find the IP addr for Google any DNS

host google.com
host yahoo.com
# filter out A, AAAA, MX etc
host -t a google.com
host -t A google.com | awk -v RS='([0-9]+\\.){3}[0-9]+' 'RT{print RT}'
var=$(host -t A google.com | awk -v RS='([0-9]+\\.){3}[0-9]+' 'RT{print RT}')
printf "%s\n" $var

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki