Ping server/domain and capture its IP on Linux

Solution 1:

This should work, from the command line or in a script:

ip=$(ping -c 1 www.google.com | gawk -F'[()]' '/PING/{print $2}')
echo $ip
173.194.34.19

EXPLANATION

First the output of the ping command being parsed:

$ ping -c 1 www.google.com
PING www.google.com (173.194.40.209) 56(84) bytes of data.
64 bytes from par10s12-in-f17.1e100.net (173.194.40.209): icmp_req=1 ttl=52 time=49.8 ms

--- www.google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 49.874/49.874/49.874/0.000 ms
  • ip=$(COMMAND) : assign the output of COMMAND to the variable $ip.
  • ping -c 1 www.google.com : ping google, once.
  • gawk is a powerful scripting language that processes input line by line and fields by field.
  • -F'[()]' : -F sets gawk's field delimiter(s). Here, we are setting it to to a character class ([ ]), specifically to open and close parentheses. This means that everything until the first ) or ( will be the first field which in gawk is $1. We are only interested in the first line so we tell gawk to print the 2nd field ($2), which is the IP, only if the current line contains "PING" (/PING/).

So, the results of the whole shebang are saved as ip which you can then refer to as $ip.