Parse ifconfig with Bash to get current IP address (wifi or ethernet)

3.4k views Asked by At

I'm trying to output my current IP address using a bash script. I'm trying to wrap my head around awk and managed the following:

/sbin/ifconfig $1 | grep "inet" | awk '$1 == "inet" {gsub(/\/.$/, "", $2); print $2}'

which outputs:

127.0.0.1
192.168.178.57

I have two issues now: First of all, 127.0.0.1 is useless, how do I get rid of it? Secondly, 192.168.178.57 is the IP address of my Wi-Fi connection. However I'd like the script to be able to grab the IP address of either Wi-Fi or Ethernet, whichever one I'm using at the moment. A sample output from /sbin/ifconfig can be found here.

4

There are 4 answers

1
fregante On

If you don't mind installing something and/or if you already have node, try sindresorhus/internal-ip

$ npm install --global internal-ip
$ internal-ip
192.168.0.2

Pro: cross-platform

Note: I know it's not bash and that it doesn't use ifconfig, but I got here looking for a generic tool to use anywhere, perhaps it can help others.

0
anubhava On

You can use this awk script:

awk '/inet / && $2 != "127.0.0.1"{print $2}' <(ifconfig)
5
Jotne On

Best way to get current used IP on a computer.

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

OLD VERSION. DO NOT USE!!!!!!

See my reply to this post: Linux bash script to extract IP address

0
Kannan Mohan On

I would suggest you to use ip command instead of ifconfig as ip is the "future" and more reliable when compared to ifconfig.

$ ip addr show dev $(ip route ls|awk '/default/ {print $5}')|grep -Po 'inet \K(\d{1,3}\.?){4}'
10.251.26.9

Here this oneliner will which the default interface using the ip route ls command and gather the interface id and based on it the IP address of that interface will be grepped.

Here the grep command uses regex to get the IP address safely.