It's neither cleaner, nor shorter really, but I think you should use ip
instead of ifconfig
. It's current, maintained, and perhaps more importantly for your purpose, it produces a consistent & parsable output.
If you want the IPv4 address for eth0
:
$ ip -4 -o addr show eth0 | awk '{print $4}'
192.168.1.166/24
which is in CIDR notation. If CIDR notation isn't wanted it can be stripped:
$ ip -4 -o addr show eth0 | awk '{print $4}' | cut -d "/" -f 1
192.168.1.166
Your question specified you wanted an address for an interface you specified. I think the answers above provide that, but if you want the IPv4 address for the host you're on, perhaps hostname
is easier/more concise:
$ hostname --all-ip-addresses | awk '{print $1}'
Or, if you want the IPv6 address:
$ hostname --all-ip-addresses | awk '{print $2}'
Finally, one other option that IMHO is "most elegant" gets the IPv4 address for whatever interface is used to connect to the specified remote host (8.8.8.8 in this case). Courtesy of @gatoatigrado in this answer:
$ ip route get 8.8.8.8 | awk '{ print $NF; exit }'
192.168.1.166
As a script:
$ RHOST=8.8.8.8
$ ip route get $RHOST | awk '{ print $NF; exit }'
Which could be useful on a host with multiple interfaces and route specifications.
ip
– Rui F Ribeiro Mar 09 '19 at 17:03