I\'m trying to find a short and robust way to put my IP address into a bash variable and was curious if there was an easier way to do this. This is how I am currently doing
Here is the best way to get IP address of an device into an variable:
ip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
NB Update to support new Linux version. (works also with older)
ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')
Why is it the best?
Hostname -I
some times get only the IP or as on my VPS it gets 127.0.0.2 143.127.52.130 2a00:dee0:ed3:83:245:70:fc12:d196
Hostnmae -I
does not work on all system.ifconfig
may not always give the IP you like.Searching of eth0
may fail if interface have other name as in VPS
server or wifi
ip route get 8.8.8.8
Tries to get route and interface to Googles DNS server (does not open any session)
Then its easy to get the ip
or interface name if you like.
This can also be used to get a ip
address of an interface to a host on a multiruted net