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
Not really shorter or simpler, but it works for me:
ip=$(ip addr show eth0 | grep -o 'inet [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' | grep -o [0-9].*)
The "eth3" is optional (useful for multiple NIC's)
ipaddress=`ip addr show eth3 | grep 'inet ' | awk '{ print $2}' | cut -d'/' -f1`
In my case I had some more interfaces in list before eth0
. By this command you can get ip4 address for any interface. For that you need to change eth0
to interface that you need.
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
You can get just awk to do all the parsing of ifconfig:
ip=$(ifconfig | gawk '
/^[a-z]/ {interface = $1}
interface == "eth0" && match($0, /^.*inet addr:([.0-9]+)/, a) {
print a[1]
exit
}
')
ip
is the right tool to use as ifconfig
has been deprecated for some time now. Here's an awk/sed/grep-free command that's significantly faster than any of the others posted here!:
ip=$(ip -f inet -o addr show eth0|cut -d\ -f 7 | cut -d/ -f 1)
(yes that is an escaped space after the first -d
)
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