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 informa
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'
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
Hostname -I
ip -4 addr show eth0 | grep -oP "(?<=inet ).*(?=/)"
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?
May be not for all cases (especially if you have several NIC's), this will help:
hostname -I | awk '{ print $1 }'