How can I assign the IP address of eth0 to an environment variable, say $ip, as easily as possible?
Update: Distro is Ubuntu Server 12.04 LTS.
How can I assign the IP address of eth0 to an environment variable, say $ip, as easily as possible?
Update: Distro is Ubuntu Server 12.04 LTS.
A shorter (and I find more neat) way is hostname -i. No more hassle with ipconfig, ip, sed, awk and such.
Using ip address show is the way to go. Especially on any modern linux system where the interface you're querying could have multiple addresses that ifconfig wouldn't know about.
$ ip a s eth0 | awk '/inet / {print$2}'
10.13.211.83/24
192.168.17.21/16
And of course if you don't want the netmask, just pipe that to any number of things, e.g.:
cut -d/ -f1
Note: On the same system, ifconfig shows:
$ ifconfig em1 | awk '/inet / {print $2}'
10.13.211.83
Try doing this :
ip=$(
ifconfig eth0 |
perl -ne 'print $1 if /inet\s.*?(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/'
)
echo "$ip"
Not answer to your exact problem as you want the IP assigned to a defined interface but I thought it could be usefull to have listed here for future info the way to have your external IP (even if behind a NAT):
ip=`wget -qO- ipecho.net/plain`
Check out also:
ifconfig eth0 | awk '/inet /{print $2}' | cut -f2 -d':'
that will work even in Solaris and HP-UX (use appropriate net dev instead of eth0).
As for hostname -i command, try hostname -I if you have one configured interface (except loopback).
As you can see, hostname -i can show 127.0.0.1 (no NAT here (archlinux)), this is not what we want.
So I propose :
dev=eth0
ip=$(
ip a s dev $dev |
awk '/inet /{gsub("/.*", "");print $2}'
)
echo "$ip"
Or if you have -P switch for grep :
ip a s dev eth0 | grep -oP 'inet\s+\K[^/]+'
I guess that's the shortest solution =)
Yon can also try this,
IP=`wget -q -O- http://checkip.dyndns.org/index.html | grep 'IP'| html2text | cut -c 21-36`