How to capture the first IP address from a ifconfig command?
It is better avoid using ifconfig
for getting an IP address in a scriptas it is deprecated in some distributions (e.g. CentOS and others, do not install it by default anymore).
In others systems, the output of ifconfig varies according to the release of the distribution (e.g. the output/spacing/fields of ifconfig
differs from Debian 8 to Debian 9, for instance).
For getting the IP address with ip
, in a similar way you are asking:
ip addr | awk ' !/127.0.0.1/ && /inet/ { gsub(/\/.*/, "", $2); print "IP="$2 } '
Or better yet:
$ ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '
192.168.1.249
Or, as you ask "IP="
#!/bin/bash
echo -n "IP="
ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print $4 } '
Adapting shamelessly the idea from @Roman
$ ip -o -4 address show | awk ' NR==2 { gsub(/\/.*/, "", $4); print "IP="$4 } '
IP=192.168.1.249
Normal output:
$ ip -o -4 address show
1: lo inet 127.0.0.1/8 scope host lo\ valid_lft forever preferred_lft forever
2: eth0 inet 192.168.1.249/24 brd 192.168.1.255 scope global eth0\ valid_lft forever preferred_lft forever
From man ip
:
-o, -oneline
output each record on a single line, replacing line feeds with the '\' character. This is convenient when you want to count records with wc(1) or to grep(1) the output.
See one example of why ifconfig
is not advised: BBB: `bbb-conf --check` showing IP addresses as `inet` - ifconfig woes
For understanding why ifconfig
is on the way out, see Difference between 'ifconfig' and 'ip' commands
ifconfig
is from net-tools, which hasn't been able to fully keep up with the Linux network stack for a long time. It also still uses ioctl for network configuration, which is an ugly and less powerful way of interacting with the kernel.Around 2005 a new mechanism for controlling the network stack was introduced - netlink sockets.
To configure the network interface
iproute2
makes use of that full-duplex netlink socket mechanism, whileifconfig
relies on an ioctl system call.
Awk
solution:
ifconfig -a | awk 'NR==2{ sub(/^[^0-9]*/, "", $2); printf "IP=%s\n", $2; exit }'
Sample output:
IP=10.0.2.15