This question already has an answer here:

I need the IP (v4) address of a device I specify. The response will be later used in a script. This is what I have:

$ IFACE=eth1
$ ifconfig $IFACE |grep "inet " | awk '{print $2}'

Is there a cleaner (shorter) way of doing this?

EDIT: ifdata is exactly what I need. Solution found here: https://unix.stackexchange.com/a/84263/126008

marked as duplicate by Rui F Ribeiro, GAD3R, Community Mar 9 at 18:12

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    If in Linux, you should be using ip – Rui F Ribeiro Mar 9 at 17:03

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}'  

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  

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 ( in this case). Courtesy of @gatoatigrado in this answer:

$ ip route get | awk '{ print $NF; exit }'

As a script:

$ RHOST=  
$ ip route get $RHOST | awk '{ print $NF; exit }'

Which could be useful on a host with multiple interfaces and route specifications.

Not the answer you're looking for? Browse other questions tagged or ask your own question.