Putting IP Address into bash variable. Is there a better way

I've been struggling with this too until I've found there's a simple command for that purpose

hostname -i

Is that simple!


ip is the right tool to use as ifconfig has been deprecated for some time now. Here's an awk/sed/grep-free command that's significantly faster than any of the others posted here!:

ip=$(ip -f inet -o addr show eth0|cut -d\  -f 7 | cut -d/ -f 1)

(yes that is an escaped space after the first -d)


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

Tags:

Bash