Jason Turley's Website

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

# you can specify which interfaces you want shown
$ ./get-ip.sh lo tun0 eth0

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:

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 ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=0.048 ms
64 bytes from icmp_seq=2 ttl=64 time=0.069 ms
64 bytes from icmp_seq=3 ttl=64 time=0.136 ms
64 bytes from icmp_seq=4 ttl=64 time=0.064 ms
64 bytes from icmp_seq=5 ttl=64 time=0.093 ms

--- 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


Here’s what is happening under the hood:

# Prints just the ip addresses for given interfaces.

    for int in $@
        ip addr show $int | grep -m 1 inet | awk '{print $2}' | cut -d / -f 1
    #   ^^ I will be focusing on this line!

# Use eth0 if no interfaces are given

if [ "$#" -ne 0 ]; then


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:


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.