w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Need to grep /etc/hosts with a known hostname, and then capture the ip address for the hostname from /etc/hosts

Simple answer

ip=$(grep 'www.example.com' /etc/hosts | awk '{print $1}')

Better answer The simple answer returns all matching IP, even those on comment lines. You probably only want the first non-comment match, in which case just use awk outright:

ip=$(awk '/^[[:space:]]*($|#)/{next} /www.example.com/{print $1; exit}' /etc/hosts)

One other thing If you, at some point, care to resolve www.example.com whether your system is configured to use hosts, dns, etc, then consider the lesser known getent command:

ip=$(getent hosts 'www.example.com' | awk '{print $1}')

Edit in response to update

$ cat script.sh

host_to_find=${1:?"Please tell me what host you want to find"}

while read ip host; do
    echo "IP=[$ip] and host=[$host]"
done < <(awk "/^[[:space:]]*($|#)/{next} /$host_to_find/{print $1 " "
$2}" /etc/hosts)

$ ./script.sh testsrv01
IP=[] and host=[testsrv01-maint]
IP=[] and host=[testsrv01-ilo]
IP=[] and host=[testsrv01-pri]
IP=[] and host=[testsrv01-sec]

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.