Setting the correct parameter

Hi Gurus,

Here is the issue that I've encountered.

VAR1=`hostname | tr '[a-z]' '[A-Z]'`
-> convert hostname to uppercase

VAR2=`grep $VAR1 /etc/hosts | awk '{ print $1 }'`
-> Since hostname is already in uppercase, grep is unable to find it in /etc/hosts. How to handle VAR2?

Is there a better way to extract the hostname and IP on separate variable?
Please kindly advice on how to extract the IP address.

Thank you.

Regards,
Peter

Peter

Do a case-insensitive search in that case:

VAR2=`grep -i $VAR1 /etc/hosts | awk '{ print $1 }'`

Guru.

1 Like

Here's my script for printing the local IP.

I prefer to get the actual address from the network device instead of the address it's supposed to be in /etc/hosts. But some of my machines have the IP address assigned to br0 device instead eth0, so I check both.

#!/bin/sh
IP="$(/sbin/ifconfig br0 2>/dev/null|grep 'inet ')"
test -z "$IP"  &&  IP="$(/sbin/ifconfig eth0|grep 'inet ')"
echo $IP | sed 's/.*addr:\([0-9.]*\).*/\1/'

Of course, If you want the result in a variable, you could capture the last line back into IP:
IP="$(echo $IP | sed 's/.*addr:\([0-9.]*\).*/\1/')"

1 Like

No need for grep if you are using gawk. You can turn case insensitivity on using IGNORECASE.

$ cat /etc/hosts
127.0.0.1       localhost
::1             localhost
....
192.168.0.115   admiralty
192.168.0.116   central
192.168.1.230   quarry
....
$ VAR1=Central
$ VAR2=$(gawk 'BEGIN {IGNORECASE=1} /'$VAR1'/ {print $1}' /etc/hosts)
$ echo $VAR2
192.168.0.116
1 Like
# grep `hostname|tr '[:lower:]' '[:upper:]'` /etc/hosts
1 Like

Hi Gurus,

Thanks a lot for your help.

I�ve managed to solve my issue.

Regards,
Peter