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
man hostname recommends using the --all-ip-addresses
flag (shorthand -I
), instead of -i
, because -i
works only if the host name can be resolved. So here it is:
hostname -I
And if you are interested only in the primary one, cut
it:
hostname -I | cut -f1 -d' '
You can take a look at this site for alternatives.
One way would be:
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
A bit smaller one, although it is not at all robust, and can return the wrong value depending on your system:
$ /sbin/ifconfig | sed -n '2 p' | awk '{print $3}'
(from http://www.htmlstaff.org/ver.php?id=22346)
my short version. Useful when you have multiple interface and just want the main ip.
host `hostname` | awk '{print $4}'
I think the most reliable answer is :
ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | awk -F: '{print $2}' | awk '{print $1}' | head -1
AND
hostname -I | awk -F" " '{print $1}'
because when you don't use head -1
it shows all ips....
I am using
IFACE='eth0'
IP=$(ip -4 address show $IFACE | grep 'inet' | sed 's/.*inet \([0-9\.]\+\).*/\1/')
The advantage of this way is to specify the interface (variable IFACE in the example) in case you are using several interfaces on your host.
Moreover, you could modify ip command in order to adapt this snippet at your convenience (IPv6 address, etc).
I've been struggling with this too until I've found there's a simple command for that purpose
hostname -i
Is that simple!