How to get my own IP address and save it to a variable in a shell script?

I believe the "modern tools" way to get your ipv4 address is to parse 'ip' rather than 'ifconfig', so it'd be something like:

ip4=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)
ip6=$(/sbin/ip -o -6 addr list eth0 | awk '{print $4}' | cut -d/ -f1)

or something like that.


Why not simply do IP=$(hostname -I) ?


It's not so easy if you want to take into account wlan and other alternative interfaces. If you know which interface you want the address for (e.g., eth0, the first Ethernet card), you can use this:

ip="$(ifconfig | grep -A 1 'eth0' | tail -1 | cut -d ':' -f 2 | cut -d ' ' -f 1)"

In other words, get me the network configuration information, look for eth0, get that line and the next one (-A 1), get only the last line, get the second part of that line when splitting with :, then get the first part of that when splitting with space.