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

I'm trying to find a short and robust way to put my IP address into a bash variable and was curious if there was an easier way to do this. This is how I am currently doing it:

ip=`ifconfig|xargs|awk '{print $7}'|sed -e 's/[a-z]*:/''/'`

Solution 1:

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

hostname -i

Is that simple!

Solution 2:

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