[linux] Linux bash script to extract IP address

I want to make big script on my Debian 7.3 ( something like translated and much more new user friendly enviroment ). I have a problem. I want to use only some of the informations that commands give me. For example my ifconfig looks like:

eth0      Link encap:Ethernet  HWaddr 08:00:27:a3:e3:b0  
          inet addr:192.168.1.103  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fea3:e3b0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1904 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2002 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:1309425 (1.2 MiB)  T

I want to display only the IP address in line: echo "Your IP address is: (IP_ADDRESS )". Is there any command that allow me to do such a thing, to search in stream for informations I want to get?. I know about grep and sed but I am not really good with them.

Edit: Firstly to say thank you for helping me with this problem, now I know much more. Secondly to say project is in progress. If anyone would be interested in it just pm me.

This question is related to linux bash sed awk

The answer is


To just get your IP address:

echo `ifconfig eth0 2>/dev/null|awk '/inet addr:/ {print $2}'|sed 's/addr://'`

This will give you the IP address of eth0.

Edit: Due to name changes of interfaces in recent versions of Ubuntu, this doesn't work anymore. Instead, you could just use this:

hostname --all-ip-addresses or hostname -I, which does the same thing (gives you ALL IP addresses of the host).


ip -4 addr show eth0 | grep -oP "(?<=inet ).*(?=/)"

ip route get 8.8.8.8| grep src| sed 's/.*src \(.* \)/\1/g'|cut -f1 -d ' '

If the goal is to find the IP address connected in direction of internet, then this should be a good solution.


UPDATE!!! With new version of linux you get more information on the line:

ip route get 8.8.8.8
8.8.8.8 via 10.36.15.1 dev ens160 src 10.36.15.150 uid 1002
    cache

so to get IP you need to find the IP after src

ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}'
10.36.15.150

and if you like the interface name

ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}'
ens192

ip route does not open any connection out, it just shows the route needed to get to 8.8.8.8. 8.8.8.8 is Google's DNS.

If you like to store this into a variable, do:

my_ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')

my_interface=$(ip route get 8.8.8.8 | awk -F"dev " 'NR==1{split($2,a," ");print a[1]}')

Why other solution may fail:

ifconfig eth0

  • If the interface you have has another name (eno1, wifi, venet0 etc)
  • If you have more than one interface
  • IP connecting direction is not the first in a list of more than one IF

Hostname -I

  • May get only the 127.0.1.1
  • Does not work on all systems.

If You want to use only sed to extract IP address:

ifconfig eth0 2>/dev/null sed -n 's/.*[[:space:]]\([[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\.[[:digit:]][[:digit:]]*\).*/\1/p'

May be not for all cases (especially if you have several NIC's), this will help:

hostname -I | awk '{ print $1 }'

awk '/inet addr:/{gsub(/^.{5}/,"",$2); print $2}' file
192.168.1.103

A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'

In my opinion the simplest and most elegant way to achieve what you need is this:

ip route get 8.8.8.8 | tr -s ' ' | cut -d' ' -f7

ip route get [host] - gives you the gateway used to reach a remote host e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3  src 192.168.0.109

tr -s ' ' - removes any extra spaces, now you have uniformity e.g.:

8.8.8.8 via 192.168.0.1 dev enp0s3 src 192.168.0.109

cut -d' ' -f7 - truncates the string into ' 'space separated fields, then selects the field #7 from it e.g.:

192.168.0.109

If you want to get a space separated list of your IPs, you can use the hostname command with the --all-ip-addresses (short -I) flag

hostname -I

as described here: Putting IP Address into bash variable. Is there a better way?


Take your pick:

$ cat file
eth0      Link encap:Ethernet  HWaddr 08:00:27:a3:e3:b0
          inet addr:192.168.1.103  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::a00:27ff:fea3:e3b0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1904 errors:0 dropped:0 overruns:0 frame:0
          TX packets:2002 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:1309425 (1.2 MiB)  T

$ awk 'sub(/inet addr:/,""){print $1}' file
192.168.1.103

$ awk -F'[ :]+' '/inet addr/{print $4}' file
192.168.1.103

Just a note, since I just spent some time trouble-shooting a botched upgrade on a server. Turned out, that (years ago) I had implemented a test to see if dynamically added interfaces (e.g. eth0:1) were present, and if so, I would bind certain proggis to the 'main' IP on eth0. Basically it was a variation on the 'ifconfig|grep...|sed... ' solution (plus checking for 'eth0:' presence).
The upgrade brought new net-tools, and with it the output has changed slightly:

old ifconfig:

eth0      Link encap:Ethernet  HWaddr 42:01:0A:F0:B0:1D
          inet addr:10.240.176.29  Bcast:10.240.176.29  Mask:255.255.255.255
          UP BROADCAST RUNNING MULTICAST  MTU:1460  Metric:1
          ...<SNIP>

whereas the new version will display this:

eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1460
      inet 10.240.212.165  netmask 255.255.255.255  broadcast 10.240.212.165
      ...<SNIP>

rendering the hunt for 'eth0:' as well as 'inet addr:' search busted (never mind interfaces called 'em0','br0' or 'wlan0'...). Sure you could check for 'inet ' (or 'inet6'), and make the addr: part optional, but looking closer, you'll see that more or less everything has changed, 'Mask' is now 'netmask',...

The 'ip route ...' suggestion's pretty nifty - so maybe:

_MyIP="$( ip route get 8.8.8.8 | awk 'NR==1 {print $NF}' )"
if [ "A$_MyIP" == "A" ]
then
    _MyIPs="$( hostname -I )"
    for _MyIP in "$_MyIPs"
    do
        echo "Found IP: \"$_MyIP\""
    done
else
    echo "Found IP: $_MyIP"
fi

Well, something of that sort anyway. Since all proposed solutions seem to have circumstances where they fail, check for possible edge cases - no eth, multiple eth's & lo's, when would 'hostname -i' fail,... and then decide on best solution, check it worked, otherwise 2nd best.

Cheers 'n' beers!


  /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to sed

Retrieve last 100 lines logs How to replace multiple patterns at once with sed? Insert multiple lines into a file after specified pattern using shell script Linux bash script to extract IP address Ansible playbook shell output remove white space from the end of line in linux bash, extract string before a colon invalid command code ., despite escaping periods, using sed RE error: illegal byte sequence on Mac OS X How to use variables in a command in sed?

Examples related to awk

What are NR and FNR and what does "NR==FNR" imply? awk - concatenate two string variable and assign to a third Printing column separated by comma using Awk command line Insert multiple lines into a file after specified pattern using shell script cut or awk command to print first field of first row How to run an awk commands in Windows? Linux bash script to extract IP address Print line numbers starting at zero using awk Trim leading and trailing spaces from a string in awk Use awk to find average of a column