BASH SCRIPT QUESTION: Determine which NIC out of multiple NICs the server hostname runs on.

I need to script finding which of the NICS on the server is the one the IP the hostname of the server runs on my Redhat 5 and Redhat 6 x86 servers. This is only part of the script since I'll use the variable for comparison later on in the script but below is how I'm going to do it. Do you think there is a better way to do it or do you think this is good enough? What I'm relying on is that $(hostname) actually matches the entry in /etc/hosts but sometimes hostname has FQDN and sometimes not.


HOSTIP=$(cat /etc/hosts | grep ${host} | awk ‘{print $1}’)
if [  ! -z ${HOSTIP} ]; then
          HOSTNIC=$(/sbin/ifconfig -a | grep -B2  ${HOSTIP} )
         printf “HOST NIC IS UNKNOWN”
         exit 1
Who is Participating?
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:
Depends on what you mean by hostname.

If you're talking about the random/useless/anything string returned from the hostname command, then usually the first IPV4 listed in ifconfig will be what you're looking to identify.

If you're talking about a true DNS lookup (far better), then use something like...

dig +short FQDN

Open in new window

Where FQDN is some domain running on machine.

Likely better to grep /etc/netplan/* or /etc/network/interfaces.d/* for first IPV4 address to pickup address which will be config'ed first during reboot.

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
lolaferrariAuthor Commented:
Great! Thanks again David!
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.