2

I'm trying to find (with awk) the IP of a specific ethernet interface using the hostname as a search patter (suffixed by the name of the ethernet interface). I wrote this little script but it outputs nothing and I don't understand why...

#!/bin/bash
name=$(hostname -s)-eth3
IP1=`awk -v var=$name '/var/ {print $1}' /etc/hosts`
echo $IP1

2 Answers 2

1

Could you please make few changes as shown following, which may help you.

#!/bin/bash
name=$(hostname -s)-eth3
IP1=$(awk -v var=$name '$0 ~ var{print $1}' "/etc/hosts")
echo "$IP1"

changes like backtick is not encouraged for storing values in bash variables $ should be used and use echo "$var" too.

Sign up to request clarification or add additional context in comments.

Comments

0

Inside slashes, awk treats var as a literal string, not a variable. Thus, replace:

/var/

With:

$0 ~ var

Thus use:

#!/bin/bash
name=$(hostname -s)-eth3
ip1=`awk -v var=$name '$0 ~ var {print $1}' /etc/hosts`
echo "$ip1"

Example

The first awk script below produces no match but the second does:

$ echo host-eth1 | awk -v var='host-eth1' '/var/ {print $1}'
$ echo host-eth1 | awk -v var='host-eth1' '$0 ~ var {print $1}'
host-eth1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.