Site icon Bytefreaks.net

Ubuntu/Bash: Get the IP of eth0

Advertisements

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 ifconfig eth0.

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

$lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 14.04.4 LTS
Release:	14.04
Codename:	trusty

The version of ifconfig for this tutorial is

$ifconfig --version
net-tools 1.60
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`;

This post is also available in: Greek

Exit mobile version