Bash: lookup an IP for a host name, including /etc/hosts in search

Ubuntu 10.10+

In my script I need to lookup an IP for a given host name.

If that name is listed in /etc/hosts, then command should print IP from /etc/hosts, not from DNS server.

What commands I tried (nslookup, dig, host), completely ignore /etc/hosts — at least for names that are not known to the DNS server.

Note: I would prefer solution that would not require me to grep /etc/hosts by hand.


getent uses the low-level glibc information functions to query all configured sources.

$ getent ahosts amd.com
163.181.249.32  STREAM amd.com
163.181.249.32  DGRAM  
163.181.249.32  RAW    
$ getent ahosts ipv6.google.com
2001:4860:b009::69 STREAM ipv6.l.google.com
2001:4860:b009::69 DGRAM  
2001:4860:b009::69 RAW    

$ gethostip localhost
localhost 127.0.0.1 7F000001
$ gethostip -d example.org
192.0.43.10

From the syslinux package, at least in Ubuntu 12.04.


This is super-hacky, but I've been using it for ages, and it works (for ipv4):

function ipfor() {
  ping -c 1 $1 | grep -Eo -m 1 '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}';
}

Use like: ipfor google.com