get-ip: a tool to print an interface's IP
Last month I made a tweet on how to get just the IP from an interface. Since then, I have updated the script and wanted to showcase it in a quick blog post.
Here’s the new script in action:
# by default it prints the IP of eth0
$ ./get-ip.sh
192.168.120.4
# you can specify which interfaces you want shown
$ ./get-ip.sh lo tun0 eth0
127.0.0.1
10.13.3.55
192.168.120.4
Don’t the ifconfig and ip commands already do this?
You may be asking yourself, “hey, isn’t this basically just the ifconfig
or ip
command?”. And you would be partially correct. However, I wrote this script for
a few reasons:
- I only wanted to display the ip addresses
ifconfig
andip
display info that isn’t always relevant (i.e. subnet, mtu)- ifconfig is deprecated and replaced by
ip addr
- to get better at bash scripting
Also, since this script only prints the IP address, you can do cool things like ping it directly!
$ ping -c 5 $(./get-ip.sh)
PING 192.168.120.4 (192.168.120.4) 56(84) bytes of data.
64 bytes from 192.168.120.4: icmp_seq=1 ttl=64 time=0.048 ms
64 bytes from 192.168.120.4: icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from 192.168.120.4: icmp_seq=3 ttl=64 time=0.136 ms
64 bytes from 192.168.120.4: icmp_seq=4 ttl=64 time=0.064 ms
64 bytes from 192.168.120.4: icmp_seq=5 ttl=64 time=0.093 ms
--- 192.168.120.4 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4197ms
rtt min/avg/max/mdev = 0.048/0.082/0.136/0.030 ms
Explanation
Here’s what is happening under the hood:
#!/bin/sh
# Prints just the ip addresses for given interfaces.
get_ip()
{
for int in $@
do
ip addr show $int | grep -m 1 inet | awk '{print $2}' | cut -d / -f 1
# ^^ I will be focusing on this line!
done
}
# Use eth0 if no interfaces are given
INTERFACE=eth0
if [ "$#" -ne 0 ]; then
INTERFACE="$@"
fi
get_ip $INTERFACE
It is not the prettiest bash script but it gets the job done. There is one line in particular I want to focus on:
ip addr show $int | grep -m 1 inet | awk '{print $2}' | cut -d / -f 1
Time to break it down:
ip addr show $int
: prints all the info for a given interfacegrep -m 1 inet
: find the first occurrance of “inet”, which should be IPv4awk '{print $2}'
: only print the second field, which is the IP addresscut -d / -f 1
: do not print the CIDR notation
Conclusion
I had a lot of fun improving this little script and seeing what other commands it could be used in conjunction with. If you find any use cases you are proud of, feel free to tweet me.