Following is a small snippet that will print on screen the IP of eth0 while in Ubuntu (Both server and desktop versions).
As you will see, it is not a very sound solution as it depends on the structure of the output of
Nevertheless is works (for Ubuntu at least)! 🙂
ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1
What this line does is: first it prints out the configuration information for eth0, then finds the line that contains the
inet addr, using
cut it gets the second column of the data after separating the line using the
: symbol. Right now in the pipe we will have something similar to this
192.168.1.37 Bcast, so we need to filter out the last part as well. We do the last filtering by using
cut again, this time by getting the first column while using the space character as the delimiter.
The Ubuntu version that was used for this tutorial is
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.4 LTS
The version of ifconfig for this tutorial is
ifconfig 1.42 (2001-04-13)
In case you want to assign the IP of eth0 to a variable, you can easily do as follows
ETH0=`ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1`;