Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

when we type " dig +short www.example.com " command we get something like that:


I want to get the first address and test it if it is what I want to (

How can I get the output of this command, especially the second line by using shell script ?

share|improve this question
up vote 7 down vote accepted

Something like this will do:

$ dig +short www.google.com | head -1

But be careful because most servers that have multiple IP addresses will do some form of round robin at the DNS level so the list is typically rotating every time you run the dig command:

$ dig +short www.google.com

$ dig +short www.google.com

$ dig +short www.google.com

Notice how the IPs move around from query to query? This is done to balance the load across those servers.

Capturing the IP into a variable

The following command will capture the output of the IP address and put it into a shell variable.

$ IP=$(dig +short www.google.com | head -1)

You can confirm this like so:

$ echo $IP
share|improve this answer
Thanks its working. – Networker Aug 31 '13 at 1:09
but how can I put it in a variable – Networker Aug 31 '13 at 1:17
@user2683768 - see updates. – slm Aug 31 '13 at 1:19

Here you go

dig +short  www.example.com | sed -n '2{p;q}'

-n prevents sed from printing its input by default. 2 causes it to execute p;q on line number 2. p stands for print and q for quit

share|improve this answer
could you explain it to me in short @1_CR – Networker Aug 31 '13 at 1:06
This prints the last line, no? echo -e "hi1\nhi2"| sed -n '2{p;q}' gives me hi2. – slm Aug 31 '13 at 1:06
@slm thanks for the edit. Explanation added. – iruvar Aug 31 '13 at 1:10
I think if you change it from a 2 to a 1 you'll get the first line. – slm Aug 31 '13 at 1:10
Yes, it's scary how much we don't know, isn't it. – slm Aug 31 '13 at 1:24

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.