BASH: parse out the serverhostname from /etc/hosts

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 gonzo gonzo.domainxxx gonzo-bk gonzo-bk.domainxxx 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?


# 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}')
       # (2)Get the IP with nslookup if it's not in /etc/hosts
       MGMTIP=$(host "$(hostname)" |  awk  '{print $5}')
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
Try this...
grep gonzo-sn foo.txt | gawk '{print $2;}'

Open in new window

nociSoftware EngineerCommented:
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 )
    MYIP=$( echo $MYLINE | (read ip remainder ; echo $ip ))
    MYIP=$( dig +short +search a $HOST )
echo $MYIP

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Prabhin MPEngineer-TechOPSCommented:
try this

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

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

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

done < $1
lolaferrariAuthor Commented:
Thank you all for your comments!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.