Use awk to figure out your ip address from ifconfig for a bash script


Objective:

Rewrite the hosts file so the host itself can use it’s external address by name.

Solution:

Find out the current IP address from ifconfig.

echo ” – `/sbin/ifconfig|awk -F “:” ‘/inet addr/{split($2,a,\” \”);print a[1]}’|head -n1` \
host host@rootninja.com”

Write out the basic stuff in hosts that doesn’t change. Just use whatever’s currently there and hardcode it below. Depending on your needs, this could be anything.

echo “127.0.0.1 localhost.localdomain localhost localhost” > /etc/hosts
echo “::1 localhost6.localdomain6 localhost6″ >> /etc/hosts

Write out the current IP address.

echo “`/sbin/ifconfig|awk -F “:” ‘/inet addr/{split($2,a,\” \”);print a[1]}’|head -n1` \
host host@rootninja.com” >> /etc/hosts

99% of the time you can just use the local address to talk to yourself. This is just an example to show you how wrangle the ip address using awk.


Posted on June 3rd, by admica in programming.
Comments Off

Comments are closed.