How to get your IP from a BASH script
For when you have many network interfaces
Published in
4 min readMay 25, 2021
The short version:
ip addr show $(ip route | awk '/default/ { print $5 }') | grep "inet" | head -n 1 | awk '/inet/ {print $2}' | cut -d'/' -f1
- We use
ip route
andawk
to determine the name of our default network interface - We use
ip addr
to get the IP details for that interface - We grep for only the line(s) that indicate “inet”
- We then make sure we are only dealing with one line via the
head
command. There should only be a single “inet” line to begin with, but it is possible there could be more than one. - We use
awk
to extract the IP address - We use
cut
to strip off the subnet information if it is present
This is a little verbose, but works very well for my use case. This can be done in a more concise manner with a little effort. Adopt this, or use another technique to suit your needs.
My Use Case
Note, I’m going to gloss over some details as being irrelevant to the conversation. The goal here is to focus on finding the IP address of the host workstation from a command line script (Bash in this case), when more than one network interface may be…