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
.
This is so elegant -- I'm using this to get the IP address from
docker.for.mac.localhost
so I can use scality/s3server with boto3 and prevent my mock s3 from thinkingdocker.for.mac
is my bucket name. – AlienWebguy – 2017-12-13T23:49:29.5201Beautiful! just what I was looking for. Thank you – ICE – 2013-06-02T03:11:37.893
4@Jim you can replace
gawk
withawk
to make it slightly more portable.gawk
might not be installed on some UNIXs butawk
should always be there. – terdon – 2013-06-02T03:18:03.3771It works like a charm! the other method I was trying with nslookup captured all ips as a single variable. It worked, but I only needed the first one.
Thank you again for your help! now I can actually move on with my script! XD – ICE – 2013-06-02T03:26:02.137