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