BASH: parse out the serverhostname from /etc/hosts

lolaferrari
lolaferrari used Ask the Experts™
on
I'm trying to parse out the hostname of the machine from /etc/hosts from /etc/hosts in order to find out the IP of the server and only use host to lookup the IP if it's not in /etc/hosts. There are multiple NICS on the server.  The issue is in the /etc/hosts it looks like this

10.12.4.15 gonzo gonzo.domainxxx
10.5.6.19 gonzo-bk gonzo-bk.domainxxx
10.10.3.19 gonzo-sn gonzo-sn.domainxxx
?
I've used grep -w to try and grep out the hostname but it still returns all the IP's in /etc/hosts. Is there a better way to parse this?

#!/bin/bash

# Get the server's IP address
if [ $( cat /etc/hosts | grep -cw $(hostname)) -ne 0 ];then
            # (1)Read the IP from the hosts file
           MGTIP=$(cat /etc/hosts | grep -w "$(hostname)" | awk '{print $1}')
else
       # (2)Get the IP with nslookup if it's not in /etc/hosts
       MGMTIP=$(host "$(hostname)" |  awk  '{print $5}')
fi
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018

Commented:
Try this...
grep gonzo-sn foo.txt | gawk '{print $2;}'

Open in new window

Software Engineer
Distinguished Expert 2018
Commented:
it needs to get more precise... if the hostname is gonzo then all lines match even on -w

so:  try this:

HOST=$( hostname )
echo $HOST
if MYLINE=$(egrep "([\t ]${HOST}[.\t ]|[\t ]${HOST}$)" /etc/hosts )
then
    MYIP=$( echo $MYLINE | (read ip remainder ; echo $ip ))
else
    MYIP=$( dig +short +search a $HOST )
fi
echo $MYIP

Open in new window

Prabhin MPDevOps Engineer
Distinguished Expert 2018

Commented:
try this
#!/bin/bash

        echo  "IP ?"
        echo -n "(Value and press Enter) :"
        read ip


while read line
do
#VARIABLES
file1=$line
mip=$(echo $file1 | awk '{print $1}')
name=$(echo $file1 | awk '{print $2}')


    if [ "$mip" = "$ip" ]
        then
        echo "Machine name is " $name
    fi

done < $1

Author

Commented:
Thank you all for your comments!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial