I'm trying to get the name of a DNS server

Using host I get this output: domain name pointer a.resolvers.level3.net

in my script, I do this as:

name="$($host $server)"

How can I use sed/awk on $name to only get the a.resolvers.level3.net, keeping in mind that I'll use this on completely different servers so I can't just grep a.resolvers out of the variable?

  • 2
    I assume the name="$($host $server)" is a typoand you're actually using name="$(host $server)", right? Also, I removed a trailing . from your host output since that looked like a typo. Please confirm that it was indeed not supposed to be there.
    – terdon
    May 3, 2017 at 9:11
  • 1
    @terdon DNS allows a trailing dot in names, and indeed host outputs them.
    – JoL
    May 3, 2017 at 18:20
  • @jlmg ah, thanks, I didn't know that.
    – terdon
    May 3, 2017 at 21:47
  • First result in Google search: stackoverflow.com/questions/12426659/… May 4, 2017 at 7:03

5 Answers 5


Another option is to slice the string :

echo ${name##* }

This will slice the string and keep the part starting from the last space to the end.

${name <-- from name  
  ##   <-- trim the front  
  *    <-- matches anything  
  ' '  <-- until the last ' '  

The simplest thing to do would be to use awk and tell it to print the last field:

$ echo "$name" | awk '{print $NF}'

Of course, if all you need is the server's IP, you may as well get that into name in the first place so you don't need to process it later:

name=$(host $server | awk '{print $NF}')
name=$(host "$server" | grep -o '[^[:space:]]*$')

will select the trailing portion of the host command's output.


Just putting a sed alternative as well. This will print last column from a string separated by whitespaces.

 sed 's/.*[[:space:]]\(.*\)$/\1/'

I tested it for cases where a.resolvers.level3.net is the only string in the $name variable and it works.

$ echo "$name" domain name pointer a.resolvers.level3.net
$ echo "$name"|sed 's/.*[[:space:]]\(.*\)$/\1/'
$ name="a.resolvers.level3.net"
$ echo "$name"|sed 's/.*[[:space:]]\(.*\)$/\1/'

A far shorter answer, involving no string manipulation at all, is

dig +short -x

which displays


and nothing more. Of course you have to have dig installed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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