linux – Grab the ipv4 address from interface

I have an active interface on eth0, by issuing ip a sh dev eth0 the information displays as below.

2: eth0:  mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
     link/ether 00:0c:29:97:69:0c brd ff:ff:ff:ff:ff:ff
     inet 192.168.1.232/24 brd 192.168.1.255 scope global dynamic noprefixroute eth0
        valid_lft 4857sec preferred_lft 4857sec
     inet6 fe80::20c:29ff:fe97:690c/64 scope link noprefixroute 
        valid_lft forever preferred_lft forever

Notice there are IPv4 (inet) and IPv6 (inet6) but I am only interested in IPv4 address, so first I shall extract the inet row by piping the ip address show dev eth0 result to grep:

ip a sh dev eth0 | grep -e "inet\s"

By using grep -e option I can put in regex, grep -e "inet\s" will display results that matches inet with a space hence inet6 will be omitted.

    inet 192.168.1.232/24 brd 192.168.1.255 scope global dynamic noprefixroute eth0

Notice there are heading spaces (tab) on the result, I want to remove the heading tabs so that it is easier to cut, by removing heading spaces I use the sed command.

ip a sh dev eth0 | grep -e "inet\s" | sed "s/[ \t]*//"

sed looks for 0 or more tabs and remove them with “//”.

The result becomes:

inet 192.168.1.232/24 brd 192.168.1.255 scope global dynamic noprefixroute eth0

Now cut this result into pieces with a delimiter ” “, then extract the ipaddress/prefix result by cutting out field 2.

ip a sh dev eth0 | grep -e "inet\s" | sed "s/[ \t]*//"| cut -d " " -f 2

The result becomes:

192.168.1.232/24

Cut further so that the prefix 24 is removed, in order to do this I cut this string with a delimiter “/” then cut out first field.

ip a sh dev eth0 | grep -e "inet\s" | sed "s/[ \t]*//"| cut -d " " -f 2|cut -d "/" -f 1

The result becomes:

192.168.1.232

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s