Tag Archives: awk

Local IP Address in Bash

How to get your local IP address in Bash

There are many ways to get your local IP address in Linux, and even more in Bash. If you know of one not mentioned here, please comment and mention it so I can add it. I’m putting this information here for future reference.

So, how do you get the local IP address on linux? Linux has a command-line command called “ifconfig” which is, basically, the linux version of Window’s “ipconfig”. Add some standard Linux commands to the mix and you can easily parse all that complicated output to give you just the local IP address for use in your Bash script. Here’s the full command:

echo $(ifconfig eth0 | grep "inet addr:" | cut --delimiter=: --fields=2 | awk '{print $1}')

If you aren’t familiar with these commands, here’s a quick overview:

  • echo” simply prints out whatever you pass to it. In this case, it will be the result of this “one liner” script.
  • ifconfig eth0″ prints out just the information about your “eth0” connection.
  • grep” widdles down our output even further, filtering out everything except the line that has our ip address in it.
  • cut” essentially splits our 1 string into an array of several strings.
  • awk” is a scripting language of it’s own, often used in Linux with a myriad of uses. In this script we’re using it to print the first string in our array (since that’s the IP address that we’re after). A note about Awk’s print function: while¬†“$0” is valid, print is not zero-based. “$0” will print the whole line, while “$1” will print the first item.

And there you have it! Running the above command would give you the local IP address of the Linux computer you’re working on, like so…

chrisanesbit@ubuntu-rocks:~$ echo $(ifconfig eth0 | grep "inet addr:" | cut --delimiter=: --fields=2 | awk '{print $1}')

And “as is” that command can be dropped right into your very own Bash script. Simply assign it to a variable instead of echoing it to StdOut and you’ve got yourself a local IP to script against!

Know of another way, maybe even a better way, to accomplish this? Leave me a comment and let me know!