How to display IP address of eth0 interface using a shell script?
How can I display the IP address shown on eth0 using a script ?
For the sake of providing another option, you could use the ip addr
command this way to get the IP address:
ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1
-
ip addr show eth0
shows information abouteth0
-
grep "inet\b"
only shows the line that has the IPv4 address (if you wanted the IPv6 address, change it to"inet6\b"
) -
awk '{print $2}'
prints on the second field, which has the ipaddress/mask, example172.20.20.15/25
-
cut -d/ -f1
only takes the IP address portion.
In a script:
#!/bin/bash
theIPaddress=$(ip addr show eth0 | grep "inet\b" | awk '{print $2}' | cut -d/ -f1)
Note: This answer is for older systems. If this does not work for you please consider other answers. This answer is not incorrect.
save this in a file and then run bash <filename>
#!/bin/bash
ifconfig eth0 | grep "inet addr"
being more accurate to get only number showing IP address:
#!/bin/bash
ifconfig eth0 | grep "inet addr" | cut -d ':' -f 2 | cut -d ' ' -f 1
Update: If this doesn't works for you, try the other answer
Update: For Ubuntu 18+, try: (don't forget to replace eth0
with interface you need the IP for. Thanks to @ignacio )
ifconfig eth0 | grep "inet " | awk '{print $2}'
Taken from https://stackoverflow.com/a/14910952/1695680
hostname -i
However that may return a local ip address (127.0.0.1), so you may have to use, and filter:
hostname -I
From hostname's manpages:
-i, --ip-address
Display the network address(es) of the host name. Note that this works only if the host name can be resolved. Avoid using this option; use hostname --all-ip-addresses instead.
-I, --all-ip-addresses
Display all network addresses of the host. This option enumerates all configured addresses on all network inter‐faces. The loopback interface and IPv6 link-local addresses are omitted. Contrary to option -i, this option does not depend on name resolution. Do not make any assumptions about the order of the output.
@markus-lindberg 's response is my favourite. If you add -o -4
to ip's flags then you get a much more easily parsable (and consistent) output:
ip -o -4 a | awk '$2 == "eth0" { gsub(/\/.*/, "", $4); print $4 }'
-o
stands for --oneline
, which is meant to help in exactly this kind of situations. The -4
is added to limit to the IPv4 address, which is what all the other responses imply.