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

Viewed 87011

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]*:/''/'`
18 Answers

On mac osx, you can use ipconfig getifaddr [interface] to get the local ip:

$ ipconfig getifaddr en0
192.168.1.30
$ man ipconfig 

DESCRIPTION
     ipconfig is a utility that communicates with the IPConfiguration agent to
     retrieve and set IP configuration parameters.  It should only be used in
     a test and debug context.  Using it for any other purpose is strongly
     discouraged.  Public API's in the SystemConfiguration framework are cur-
     rently the only supported way to access and control the state of IPCon-
     figuration.

     ...

     getifaddr interface-name
                 Prints to standard output the IP address for the first net-
                 work service associated with the given interface.  The output
                 will be empty if no service is currently configured or active
                 on the interface.
Related