Putting IP Address into bash variable. Is there a better way - bash

I'm trying to find a short and robust way to put my IP address into a bash variable and was curious if there was an easier way to do this. This is how I am currently doing it:
ip=`ifconfig|xargs|awk '{print $7}'|sed -e 's/[a-z]*:/''/'`

I've been struggling with this too until I've found there's a simple command for that purpose
hostname -i
Is that simple!

man hostname recommends using the --all-ip-addresses flag (shorthand -I ), instead of -i, because -i works only if the host name can be resolved. So here it is:
hostname -I
And if you are interested only in the primary one, cut it:
hostname -I | cut -f1 -d' '

ip is the right tool to use as ifconfig has been deprecated for some time now. Here's an awk/sed/grep-free command that's significantly faster than any of the others posted here!:
ip=$(ip -f inet -o addr show eth0|cut -d\ -f 7 | cut -d/ -f 1)
(yes that is an escaped space after the first -d)

You can take a look at this site for alternatives.
One way would be:
ifconfig | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'
A bit smaller one, although it is not at all robust, and can return the wrong value depending on your system:
$ /sbin/ifconfig | sed -n '2 p' | awk '{print $3}'
(from http://www.htmlstaff.org/ver.php?id=22346)

The ifdata command (found in the moreutils package) provides an interface to easily retrieve ifconfig data without needing to parse the output from ifconfig manually. It's achieved with a single command:
ifdata -pa eth1
Where eth1 is the name of your network interface.
I don't know how this package behaves when ifconfig is not installed. As Syncrho stated in his answer, ifconfig has been deprecated for sometime, and is no longer found on a lot of modern distributions.

Here is the best way to get IP address of an device into an variable:
ip=$(ip route get 8.8.8.8 | awk 'NR==1 {print $NF}')
NB Update to support new Linux version. (works also with older)
ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')
Why is it the best?
Hostname -I some times get only the IP or as on my VPS it gets 127.0.0.2 143.127.52.130 2a00:dee0:ed3:83:245:70:fc12:d196
Hostnmae -I does not work on all system.
Using ifconfig may not always give the IP you like.
a. It will fail you have multiple interface (wifi/etcernet) etc.
b. Main IP may not be on the first found interface
Searching of eth0 may fail if interface have other name as in VPS server or wifi
ip route get 8.8.8.8
Tries to get route and interface to Googles DNS server (does not open any session)
Then its easy to get the ip or interface name if you like.
This can also be used to get a ip address of an interface to a host on a multiruted net

my short version. Useful when you have multiple interface and just want the main ip.
host `hostname` | awk '{print $4}'

You can get just awk to do all the parsing of ifconfig:
ip=$(ifconfig | gawk '
/^[a-z]/ {interface = $1}
interface == "eth0" && match($0, /^.*inet addr:([.0-9]+)/, a) {
print a[1]
exit
}
')

Not really shorter or simpler, but it works for me:
ip=$(ip addr show eth0 | grep -o 'inet [0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+' | grep -o [0-9].*)

The following works on Mac OS (where there is no ip commnand or hostname options):
#!/bin/bash
#get interface used for defalt route (usually en0)
IF=$(route get default |grep 'interface' |awk -F: '{print $2}');
#get the IP address for inteface IF
#does ifconfig, greps for interface plus 5 lines, greps for line with 'inet '
IP=$(ifconfig |grep -A5 $IF | grep 'inet ' | cut -d: -f2 |awk '{print $2}');
#get the gateway for the default route
GW=$(route get default | awk '/gateway:/ {print $2}');

ifconfig | grep -oP "(?<=inet addr:).*?(?= Bcast)"
When using grep to extract a portion of a line (as some other answers do), perl look-ahead and look-behind assertions are your friends.
The quick explanation is that the first (?<=inet addr:) and last (?= Bcast) parenthesis contain patterns that must be matched, but the characters that match those patters won't be returned by grep, only the characters that are between the two patterns and match the pattern .*? that is found between the sets of parenthesis, are returned.
Sample ifconfig output:
eth0 Link encap:Ethernet HWaddr d0:67:e5:3f:b7:d3
inet addr:10.0.0.114 Bcast:10.0.0.255 Mask:255.255.255.0
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1392392 errors:0 dropped:0 overruns:0 frame:0
TX packets:1197193 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1294730881 (1.2 GB) TX bytes:167208753 (167.2 MB)
Interrupt:18
This will extract your IP address from the ifconfig output:
ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)"
To assign that to a variable, use this:
ip=$(ifconfig | grep -oP "(?<=inet addr:).*?(?=Bcast)")
A slightly more in depth explanation:
From man grep:
-o Print only the matched (non-empty) parts of matching lines, with each such part on a separate output line.
-P Interpret the pattern as a Perl regular expression. This is highly experimental and ‘grep -P’ may warn of unimplemented features.
From permonks.org:
(?<=pattern) is a positive look-behind assertion
(?=pattern) is a positive look-ahead assertion
-o Tells grep to only return the portion of the line that matches the pattern. The look-behinds/aheads are not considered by grep to be part of the pattern that is returned. The ? after .* is important since we want it to look for the very next look-ahead after the .* pattern is matched, and not look for the last look-ahead match. (This is not needed if we added a regex for the IP address instead of .*, but, readability).

I am using
IFACE='eth0'
IP=$(ip -4 address show $IFACE | grep 'inet' | sed 's/.*inet \([0-9\.]\+\).*/\1/')
The advantage of this way is to specify the interface (variable IFACE in the example) in case you are using several interfaces on your host.
Moreover, you could modify ip command in order to adapt this snippet at your convenience (IPv6 address, etc).

I think the most reliable answer is :
ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | awk -F: '{print $2}' | awk '{print $1}' | head -1
AND
hostname -I | awk -F" " '{print $1}'
because when you don't use head -1 it shows all ips....

In my script i did need only the network part of the IP, so I did it like that
local=$(hostname -I | awk '{print $2}' | cut -f1,2,3 -d".")
Where the cut -f1,2,3 -d"." can be read as "get first 3 parts separated by commas"
To change interfaces just change $2 to your interface number, to get whole IP remove cut.

In trying to avoid too many pipes, work on various linuxes, set an exit code, and avoiding ifconfig or other packages, I tried the whole thing in awk:
ip addr show | awk '
BEGIN {FS="/"}
/^[0-9]+: eth[0-9]+.*UP*/ {ss=1}
ss==1 && /^ +inet / {print substr($1,10); exit 0}
END {exit 1}'
and note that a particular interface can be specified after "ip addr show" if you don't want just the first eth interface. And adapting to ipv6 is a matter of looking for "inet6" instead of "inet"...

On mac osx, you can use ipconfig getifaddr [interface] to get the local ip:
$ ipconfig getifaddr en0
192.168.1.30
$ man ipconfig
DESCRIPTION
ipconfig is a utility that communicates with the IPConfiguration agent to
retrieve and set IP configuration parameters. It should only be used in
a test and debug context. Using it for any other purpose is strongly
discouraged. Public API's in the SystemConfiguration framework are cur-
rently the only supported way to access and control the state of IPCon-
figuration.
...
getifaddr interface-name
Prints to standard output the IP address for the first net-
work service associated with the given interface. The output
will be empty if no service is currently configured or active
on the interface.

In my case I had some more interfaces in list before eth0. By this command you can get ip4 address for any interface. For that you need to change eth0 to interface that you need.
/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'

The "eth3" is optional (useful for multiple NIC's)
ipaddress=`ip addr show eth3 | grep 'inet ' | awk '{ print $2}' | cut -d'/' -f1`

If by "my ip address" you mean "the IP address my machine will use to get to the public Internet to which I am connected", then this very tidy JSON answer may work for you, depending on what O/S your machine runs:
ip=$( ip -j route get 8.8.8.8 | jq -r '.[].prefsrc' )
It does require an ip command that produces JSON output (some say the BusyBox ip command cannot do this), the CLI jq parser that can extract fields from JSON input, and your machine has to know how to get to the public IP at 8.8.8.8.
If you want the IP address your machine would use to get to some other place, such as a local network, put that other IP in place of the public IP 8.8.8.8, e.g.
ip=$( ip -j route get 192.168.1.1 | jq -r '.[].prefsrc' )
ip=$( ip -j route get 10.1.2.3 | jq -r '.[].prefsrc' )
If you only have one interface, then most any non-localhost IP address should work to get your IP address.
Parsing the JSON output with jq is so much simpler than all those complex examples with sed, awk, and grep, but the more complex examples do use tools that are present by default on almost all Unix/Linux/BSD systems.

assuming you have something like curl or wget, then one easy way to get external IP addresses with no downstream parsing necessary would be :
— (wildcard syntax for wget might differ)
curl -w '\n\n%{url_effective}\n\n' -s 'http://api{,6}.ipify.org'
98.xxx.132.255
http://api.ipify.org/
2603:7000:xxxx:xxxx:xxxx:c80f:1351:390d
http://api6.ipify.org/
Yielding both IPv4 and IPv6 addresses in one shot

Related

How to get ip address of a server on Centos 7 in bash

Previously I used the following command in bash to find the main ip of my server
ipaddr=$(/sbin/ifconfig|grep inet|head -1|sed 's/\:/ /'|awk '{print $3}' | grep -v '127.0.0.1')
But in centos7 it no longer works since ifconfig isn't available and the command no longer works even if I install ifconfig using yum install net-tools
What is the equivalent command for centos 7
Thanks a lot
You can use hostname command :
ipaddr=$(hostname -I)
-i, --ip-address:
Display the IP address(es) of the host. Note that this works only if the host name can be resolved.
-I, --all-ip-addresses:
Display all network addresses of the host. This option enumerates all configured addresses on all network interfaces. 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.
Ref: https://garbagevalue.com/blog/4-simle-ways-to-check-ip-adress-in-centos-7
I'm using CentOS 7 and command
ip a
is enough to do the job.
Edit
Just slice out the IP address part from that test.
ip a | grep 192
Enter the command ip addr at the console
hostname -I | awk ' {print $1}'
Something like this - a riff on #maarten-vanlinthout's answer
ip -f inet a show eth0| grep inet| awk '{ print $2}' | cut -d/ -f1
SERVER_IP="$(ip addr show ens160 | grep 'inet ' | cut -f2 | awk '{ print $2}')"
replace ens160 with your interface name
You can run simple commands like
curl ifconfig.co
curl ifconfig.me
wget -qO - icanhazip.com
Actually, when you do not want to use external sources (or cannot), I would recommend:
DEVICE=$(ls -l /sys/class/net | awk '$NF~/pci0/ { print $(NF-2); exit }')
IPADDR=$(ip -br address show dev $DEVICE | awk '{print substr($3,1,index($3,"/")-1);}')
The first line gets the name of the first network device on the PCI bus, the second one gives you its IP address.
BTW ps ... | grep ... | awk ...
stinks. awk does not need grep.
Bit late however I use
curl -4 icanhazip.com
returns the server Primary IP address.
I believe that the most reliable way to get the external server ip address would be to use an external service.
ipaddr=$(curl -s http://whatismyip.akamai.com/)
Run this command to show ip4 and ip6:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1

Which terminal command to get just IP address and nothing else?

I'm trying to use just the IP address (inet) as a parameter in a script I wrote.
Is there an easy way in a unix terminal to get just the IP address, rather than looking through ifconfig?
You can write a script that only return the IP like:
/sbin/ifconfig eth0 | grep 'inet addr' | cut -d: -f2 | awk '{print $1}'
For MAC:
ifconfig | grep "inet " | grep -v 127.0.0.1 | cut -d\ -f2
Or for linux system
hostname -i | awk '{print $3}' # Ubuntu
hostname -i # Debian
This will give you all IPv4 interfaces, including the loopback 127.0.0.1:
ip -4 addr | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
This will only show eth0:
ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'
And this way you can get IPv6 addresses:
ip -6 addr | grep -oP '(?<=inet6\s)[\da-f:]+'
Only eth0 IPv6:
ip -6 addr show eth0 | grep -oP '(?<=inet6\s)[\da-f:]+'
Generally, it is never guaranteed that a system will only have one IP address, for example, you can have both an ethernet and wlan connections, and if you have an active VPN connection then you'll have yet another IP address.
Linux
On Linux, hostname -I will list the current IP address(es). Relying on it always returning just one IP address will most likely not work as expected under some scenarios (i.e. a VPN link is up, multiple ethernet adapters, etc), so a more reliable way would be converting the result to an array and then loop over the elements:
ips=($(hostname -I))
for ip in "${ips[#]}"
do
echo $ip
done
Note: If hostname -I returns the IP both in IPv4 and IPv6 formats then you can use instead hostname -I | cut -f1 -d' ' to only show the IPv4 IP.
OSX
On OSX, if you know the interface, you could use:
~$ ipconfig getifaddr en0
# OUTPUT: 192.168.1.123
which will return just the IP address.
To detect dynamically the (first) active network interface on MacOS:
network_device=$(scutil --dns |awk -F'[()]' '$1~/if_index/ {print $2;exit;}')
ip=$(ipconfig getifaddr "$network_device")
echo $ip
### OUTPUT: 192.168.1.123
Also, getting the IP address becomes non-deterministic in case both a cable and wifi connections are established, when a machine has more than one ethernet interfaces, or when VPN tunnels are up.
Getting the external IP
If you need the external IP, then you can query a text-mode service, for example curl https://ipecho.net/plain would return a plain text external IP.
A possibly faster alternative is to query a known DNS server, e.g.:
dig #ns1-1.akamaitech.net ANY whoami.akamai.net +short
hostname -I
This command will give you the exact ip address as you want in Ubuntu.
On latest Ubuntu versions (14.04 - 16.04), this command did the trick for me.
hostname -I | awk '{print $1}'
To get only the IP address on Mac OS X you can type the following command:
ipconfig getifaddr en0
If you have limited environment, you may use this command:
ip -4 addr show dev eth0 | grep inet | tr -s " " | cut -d" " -f3 | head -n 1
Command ifconfig is deprected and you should use ip command on Linux.
Also ip a will give you scope on the same line as IP so it's easier to use.
This command will show you your global (external) IP:
ip a | grep "scope global" | grep -Po '(?<=inet )[\d.]+'
All IPv4 (also 127.0.0.1):
ip a | grep "scope" | grep -Po '(?<=inet )[\d.]+'
All IPv6 (also ::1):
ip a | grep "scope" | grep -Po '(?<=inet6 )[\da-z:]+'
I prefer not to use awk and such in scripts.. ip has the option to output in JSON.
If you leave out $interface then you get all of the ip addresses:
ip -json addr show $interface | \
jq -r '.[] | .addr_info[] | select(.family == "inet") | .local'
ip -4 addr show eth0 doesn't work on some machines. For example, I get this error:
ip: symbol lookup error: ip: undefined symbol: bpf_program__section_name, version LIBBPF_0.2.0
This works for me:
/sbin/ifconfig eth0 | grep 'inet ' | awk '{ print $2}'
This has one less pipe than the accepted answer. In addition, my ifconfig output does not have inet addr.
To get the IPv6 address, use this:
/sbin/ifconfig eth0 | grep 'inet6 ' | awk '{ print $2}'
I wanted something simple that worked as a Bash alias. I found that hostname -I works best for me (hostname v3.15). hostname -i returns the loopback IP, for some reason, but hostname -I gives me the correct IP for wlan0, and without having to pipe output through grep or awk. A drawback is that hostname -I will output all IPs, if you have more than one.
We can simply use only 2 commands ( ifconfig + awk ) to get just the IP (v4) we want like so:
On Linux, assuming to get IP address from eth0 interface, run the following command:
/sbin/ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'
On OSX, assumming to get IP adddress from en0 interface, run the following command:
/sbin/ifconfig en0 | awk '/inet /{print $2}'
To know our public/external IP, add this function in ~/.bashrc
whatismyip () {
curl -s "http://api.duckduckgo.com/?q=ip&format=json" | jq '.Answer' | grep --color=auto -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
}
Then run, whatismyip
Few answers appear to be using the newer ip command (replacement for ifconfig) so here is one that uses ip addr, grep, and awk to simply print the IPv4 address associated with the wlan0 interface:
ip addr show wlan0|grep inet|grep -v inet6|awk '{print $2}'|awk '{split($0,a,"/"); print a[1]}'
While not the most compact or fancy solution, it is (arguably) easy to understand (see explanation below) and modify for other purposes, such as getting the last 3 octets of the MAC address like this:
ip addr show wlan0|grep link/ether|awk '{print $2}'|awk '{split($0,mac,":"); print mac[4] mac[5] mac[6]}'
Explanation: ip addr show wlan0 outputs information associated with the network interface named wlan0, which should be similar to this:
4: wlan0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether dc:a6:32:04:06:ab brd ff:ff:ff:ff:ff:ff
inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
valid_lft forever preferred_lft forever
inet6 fe80::d340:5e4b:78e0:90f/64 scope link
valid_lft forever preferred_lft forever
Next grep inet filters out the lines that don't contain "inet" (IPv4 and IPv6 configuration) and grep -v inet6 filters out the remaining lines that do contain "inet6", which should result in a single line like this one:
inet 172.18.18.1/24 brd 172.18.18.255 scope global noprefixroute wlan0
Finally, the first awk extract the "172.18.18.1/24" field and the second removes the network mask shorthand, leaving just the IPv4 address.
Also, I think it's worth mentioning that if you are scripting then there are often many richer and/or more robust tools for obtaining this information, which you might want to use instead. For example, if using Node.js there is ipaddr-linux, if using Ruby there is linux-ip-parser, etc.
See also https://unix.stackexchange.com/questions/119269/how-to-get-ip-address-using-shell-script
To print only the IP address of eth0, without other text:
ifconfig eth0 | grep -Po '(?<=inet addr:)[\d.]+'
To determine your primary interface (because it might not be "eth0"), use:
route | grep ^default | sed "s/.* //"
The above two lines can be combined into a single command like this:
ifconfig `route | grep ^default | sed "s/.* //"` \
| grep -Po '(?<=inet addr:)[\d.]+'
That would do the trick in a Mac :
ping $(ifconfig en0 | awk '$1 == "inet" {print $2}')
That resolved to ping 192.168.1.2 in my machine.
Pro tip: $(...) means run whatever is inside the parentheses in a subshell and return that as the value.
I always wind up needing this at the most unexpected times and, without fail, wind up searching for threads like this on SO. So I wrote a simple script to get IPv4 addresses via netstat, called echoip - you can find it here. The bash for network addresses looks like this, it also gets your public address from ipecho.net:
IPV4='\d+(\.\d+){3}'
INTERFACES=`netstat -i | grep -E "$IPV4" | cut -d ' ' -f 1`
INTERFACE_IPS=`netstat -i | grep -oE "$IPV4"`
for i in "${!INTERFACES[#]}"; do
printf "%s:\t%s\n" "${INTERFACES[$i]}" "${INTERFACE_IPS[$i]}"
done
The echoip script yields an output like this:
$ echoip
public: 26.106.59.169
en0: 10.1.10.2
In man hostname there is even more easier way which automatically excluding loopback IP and showing only space separated list of all assigned to host ip addresses:
root#srv:~# hostname --all-ip-addresses
11.12.13.14 192.168.15.19
root#srv:~# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: venet0: <BROADCAST,POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN
link/void
inet 11.12.13.14/32 scope global venet0:0
inet 192.168.15.19/32 scope global venet0:1
the easiest way is as Mikko said
hostname --all-ip-addresses
the output
you can also do that for little more details :
ip route
the output
Use the following command:
/sbin/ifconfig $(netstat -nr | tail -1 | awk '{print $NF}') | awk -F: '/inet /{print $2}' | cut -f1 -d ' '
Here is my version, in which you can pass a list of interfaces, ordered by priority:
getIpFromInterface()
{
interface=$1
ifconfig ${interface} > /dev/null 2>&1 && ifconfig ${interface} | awk -F'inet ' '{ print $2 }' | awk '{ print $1 }' | grep .
}
getCurrentIpAddress(){
IFLIST=(${#:-${IFLIST[#]}})
for currentInterface in ${IFLIST[#]}
do
IP=$(getIpFromInterface $currentInterface)
[[ -z "$IP" ]] && continue
echo ${IP/*:}
return
done
}
IFLIST=(tap0 en1 en0)
getCurrentIpAddress $#
So if I'm connected with VPN, Wifi and ethernet, my VPN address (on interface tap0) will be returned. The script works on both linux and osx, and can take arguments if you want to override IFLIST
Note that if you want to use IPV6, you'll have to replace 'inet ' by 'inet6'.
use this one line script:
ifconfig | grep "inet " | grep -v 127.0.0.1|awk 'match($0, /([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/) {print substr($0,RSTART,RLENGTH)}'
mac & linux (tested in ubuntu) both works.
You can also use the following command:
ip route | grep src
NOTE: This will only work if you have connectivity to the internet.
The IPv4 address for the default route:
ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet )[^ /]+"
The IPv6 address for the default route:
ip address show $(ip route | grep "^default " | head -n1 | grep -Po "(?<=dev )[^ ]+") | grep -Po "(?<=inet6 )[^ /]+"
These only require commands ip and grep with support for -P and -o. The head -1 is required because ip route may show multiple default routes when system has complex enough network setup.
If you don't mind which IP is which, you can just do
ip route | grep -Po '(?<=src )[^ ]+'
or
hostname --all-ip-addresses
ip adddr, the short way
ip -4 -br addr show enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1
or shorten
ip -4 -br a s enp1s0 | awk -F" " '{print $3}'|cut -d'/' -f1
must work in most modern Linux distribution
I don't see any answer with nmcli yet which is a command-line tool for controlling NetworkManager.
So here you go :)
wolf#linux:~$ nmcli device
DEVICE TYPE STATE CONNECTION
eth1 ethernet unavailable --
eth0 ethernet unmanaged --
lo loopback unmanaged --
wolf#linux:~$
If you want to get the information from specific network interface (let say lo for this example)
wolf#linux:~$ nmcli device show lo
GENERAL.DEVICE: lo
GENERAL.TYPE: loopback
GENERAL.HWADDR: 00:00:00:00:00:00
GENERAL.MTU: 65536
GENERAL.STATE: 10 (unmanaged)
GENERAL.CONNECTION: --
GENERAL.CON-PATH: --
IP4.ADDRESS[1]: 127.0.0.1/8
IP4.GATEWAY: --
IP4.ROUTE[1]: dst = 127.0.0.0/8, nh = 0.0.0.0,>
IP4.ROUTE[2]: dst = 127.0.0.1/32, nh = 0.0.0.0>
IP6.ADDRESS[1]: ::1/128
IP6.GATEWAY: --
IP6.ROUTE[1]: dst = ::1/128, nh = ::, mt = 256
IP6.ROUTE[2]: dst = ::1/128, nh = ::, mt = 0, >
wolf#linux:~$
But since you just want to get the IP address, just send the output to grep, cut or awk.
Let's do it step by step. (Not sure what's wrong, the code sample format just didn't work for these 3 example.)
Get the IPv4 line
wolf#linux:~$ nmcli device show lo | grep 4.A
IP4.ADDRESS[1]: 127.0.0.1/8
wolf#linux:~$
Use awk to get the IP
wolf#linux:~$ nmcli device show lo | awk '/4.A/ {print $2}'
127.0.0.1/8
wolf#linux:~$
Use cut to remove the CIDR notation (/8)
wolf#linux:~$ nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1
127.0.0.1
wolf#linux:~$
There your answer.
Please take note that there are tons of ways to do it using the tools that I demonstrated just now.
Let's recap the commands that I used.
nmcli device show lo | grep 4.A
nmcli device show lo | awk '/4.A/ {print $2}'
nmcli device show lo | awk '/4.A/ {print $2}' | cut -d / -f1
Sample output for these 3 commands
Command 1 output
IP4.ADDRESS[1]: 127.0.0.1/8
Command 2 output
127.0.0.1/8
Command 3 output
127.0.0.1
ip addr|awk '/eth0/ && /inet/ {gsub(/\/[0-9][0-9]/,""); print $2}'
shows all your ips
On Redhat 64bit, this solved problem for me.
ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'
#!/bin/sh
# Tested on Ubuntu 18.04 and Alpine Linux
# List IPS of following network interfaces:
# virtual host interfaces
# PCI interfaces
# USB interfaces
# ACPI interfaces
# ETH interfaces
for NETWORK_INTERFACE in $(ls /sys/class/net -al | grep -iE "(/eth[0-9]+$|vif|pci|acpi|usb)" | sed -E "s#.* ([^ ]*) ->.*#\1#"); do
IPV4_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet addr[: ]+|inet[: ]+)' | sed -E "s#\s*(inet addr[: ]+|inet[: ]+)([^ ]*) .*#\2#")
IPV6_ADDRESSES=$(ifconfig $NETWORK_INTERFACE | grep -iE '(inet6 addr[: ]+|inet6[: ]+)' | sed -E "s#\s*(inet6 addr[: ]+|inet6[: ]+)([^ ]*) .*#\2#")
if [ -n "$IPV4_ADDRESSES" ] || [ -n "$IPV6_ADDRESSES" ]; then
echo "NETWORK INTERFACE=$NETWORK_INTERFACE"
for IPV4_ADDRESS in $IPV4_ADDRESSES; do
echo "IPV4=$IPV4_ADDRESS"
done
for IPV6_ADDRESS in $IPV6_ADDRESSES; do
echo "IPV6=$IPV6_ADDRESS"
done
fi
done
When looking up your external IP address on a NATed host, quite a few answers suggest using HTTP based methods like ifconfig.me eg:
$ curl ifconfig.me/ip
Over the years I have seen many of these sites come and go, I find this DNS based method more robust:
$ dig +short myip.opendns.com #resolver1.opendns.com
I have this handy alias in my ~/.bashrc:
alias wip='dig +short myip.opendns.com #resolver1.opendns.com'
These two ways worked for me:
To get IP address of your interface eth0. Replace eth0 in the below example with your interface name.
ifconfig eth0 | grep -w "inet" | tr -s " " | cut -f3 -d" "
Using hostname:
This will give you the inet i.e. IPAddress of your etho. using -I will give you inet value of all the interfaces whereever this value is present.
hostname -i

Bash script issue

I can run this command fine, with the output I want:
ifconfig eth0 | grep HWaddr | awk '{print $5}'
However, when I set the command to a variable, and print the variable, I get an error:
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
$CASS_INTERNAL
my internal xxx ip: command not found
The weird thing - my internal IP actually shows up. How do I go about this without getting an error? It shouldn't matter, but I'm using the latest version of Ubuntu.
You're not printing the variable, you're running it as a command name. You're looking for
echo "$CASS_INTERNAL"
(Get into the habit of always putting double quotes around variable substitutions.)
More advanced shell note: in this case it doesn't matter, but in general echo can have trouble with some special characters (- and \\), so it's better to use the following more complicated but fully reliable command:
printf "%s\n" "$CASS_INTERNAL"
don't have to use grep
ifconfig eth0 | awk '/HWaddr/{print $5}'
CASS_INTERNAL=`ifconfig eth0 | grep HWaddr | awk '{print \$5}'`
echo $CASS_INTERNAL
Your:
$CASS_INTERNAL
Would try to run it as a command.
do you maybe want
echo $CASS_INTERNAL
Well, you grep for HWaddr first, so the fifth field on this this line is the MAC address of the network adapter in question - not your local IP address.
Others have suggested the solution is to simply echo the result, meaning if eth0 in this example is not available at that point in time which the line gets executed, it will not work.
From what I understand you wish instead to put the desired command line in a variable, then evaluate it later on. This pattern is commonly called lazy evaluation, and is made possible in bash by using the eval builtin:
#put the desired command in variable
CASS_INTERNAL='ifconfig eth0 | grep HWaddr | awk "{print \$5}"'
# ....
#at later on - evaluate its contents!
eval $CASS_INTERNAL
11:22:33:aa:bb:cc

How to Grab MAC Address of Active Ethernet Connection in Bash Script?

Simple Question:
How do I grab the MAC address of the active Ethernet connection in a bash script?
I currently have:
set - `/sbin/ifconfig eth0 | head -1`
MAC=$5
Which outputs the MAC address of the eth0, but if it's eth1 that's active, I want that instead.
Could I beforehand execute ifconfig | grep inet but that wouldn't tell me which interface is active, just that one is active. I need to grab the line above it to tell me which one is the active connection.
Any help would be much appreciated.
Thank you!
Found the answer:
set - `ifconfig | grep -B 1 inet | head -1`
MAC=$5
I grep'd the inet string and returned the line before. Then use head to grab the first line.
you could do something like this
ifconfig | awk '/eth/ { print $5 }'
also an option... depending on user may need to specify /sbin/ifconfig in the xargs
route | awk '/default/ { print $NF }' | xargs -I {} ifconfig {} | awk '/HWaddr/ { print $5 }'

How do I get the default gateway in Linux given the destination?

I'm trying to get the default gateway, using the destination 0.0.0.0.
I used the command netstat -rn | grep 0.0.0.0 and it returned this list:
Destination Gateway Genmask Flags MSS Window irtt Iface
10.9.9.17 0.0.0.0 255.255.255.255 UH 0 0 0 tun0
133.88.0.0 0.0.0.0 255.255.0.0 U 0 0 0 eth0
0.0.0.0 133.88.31.70 0.0.0.0 UG 0 0 0 eth0
My goal here is to ping the default gateway using the destination 0.0.0.0, which is 133.88.31.70, but this one returns a list because of using grep.
How do I get the default gateway only? I need it for my Bash script to determine whether the network connection is up or not.
You can get the default gateway using ip command like this:
IP=$(/sbin/ip route | awk '/default/ { print $3 }')
echo $IP
The ip route command from the iproute2 package can select routes without needing to use awk/grep, etc to do the selection.
To select the default route (from possibly many):
$ ip -4 route show default # use -6 instead of -4 for ipv6 selection.
default via 172.28.206.254 dev wlp0s20f3 proto dhcp metric 600
To select the next hop for a particular interface:
$ ip -4 route list type unicast dev eth0 exact 0/0 # Exact specificity
default via 172.29.19.1 dev eth0
In case of multiple default gateways, you can select which one gets chosen as the next hop to a particular destination address:
$ ip route get $(dig +short google.com | tail -1)
173.194.34.134 via 172.28.206.254 dev wlan0 src 172.28.206.66
cache
You can then extract the value using sed/awk/grep, etc. Here is one example using bash's read builtin:
$ read _ _ gateway _ < <(ip route list match 0/0); echo "$gateway"
172.28.206.254
works on any linux:
route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " "
This simple perl script will do it for you.
#!/usr/bin/perl
$ns = `netstat -nr`;
$ns =~ m/0.0.0.0\s+([0-9]+.[0-9]+.[0-9]+.[0-9]+)/g;
print $1
Basically, we run netstat, save it to $ns. Then find the line that starts off with 0.0.0.0. Then the parentheses in the regex saves everything inside it into $1. After that, simply print it out.
If it was called null-gw.pl, just run it on the command like:
perl null-gw.pl
or if you need it inside a bash expression:
echo $(perl null-gw.pl)
Good luck.
This is how I do it:
#!/bin/sh
GATEWAY_DEFAULT=$(ip route list | sed -n -e "s/^default.*[[:space:]]\([[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\).*/\1/p")
echo ${GATEWAY_DEFAULT}
For a list of all default gateways, use mezgani's answer, duplicated (and slightly simplified) here:
/sbin/ip route | awk '/^default/ { print $3 }'
If you have multiple network interfaces configured simultaneously, this will print multiple gateways. If you want to select a single known network interface by name (e.g. eth1), simply search for that in addition to filtering for the ^default lines:
/sbin/ip route |grep '^default' | awk '/eth1/ {print $3}'
You can make a script that takes a single network-interface name as an argument and prints the associated gateway:
#!/bin/bash
if [[ $# -ne 1 ]]; then
echo "ERROR: must specify network interface name!" >&2
exit 1
fi
# The third argument of the 'default' line associated with the specified
# network interface is the Gateway.
# By default, awk does not set the exit-code to a nonzero status if a
# specified search string is not found, so we must do so manually.
/sbin/ip route | grep '^default' | awk "/$1/ {print \$3; found=1} END{exit !found}"
As noted in the comments, this has the advantage of setting a sensible exit-code, which may be useful in a broader programmatic context.
There are a lot of answers here already. Some of these are pretty distro specific. For those who found this post looking for a way to find the gateway, but not needing to use it in code/batch utilization (as I did)... try:
traceroute www.google.com
the first hop is your default gateway.
The following command returns the default route gateway IP on a Linux host using only bash and awk:
printf "%d.%d.%d.%d" $(awk '$2 == 00000000 && $7 == 00000000 { for (i = 8; i >= 2; i=i-2) { print "0x" substr($3, i-1, 2) } }' /proc/net/route)
This should even work if you have more than one default gateway as long as their metrics are different (and they should be..).
Another perl thing:
$return = (split(" ", `ip route | grep default`))[2];<br>
Note: use these backticks before ip and after default
netstat -rn | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"
#!/bin/bash
##################################################################3
# Alex Lucard
# June 13 2013
#
# Get the gateway IP address from the router and store it in the variable $gatewayIP
# Get the Router mac address and store it in the variable gatewayRouter
# Store your routers mac address in the variable homeRouterMacAddress
#
# If you need the gateway IP uncomment the next line to get the gateway address and store it in the variable gateWayIP
# gatewayIP=`sudo route -n | awk '/^0.0.0.0/ {print $2}'`
homeRouterMacAddress="20:aa:4b:8d:cb:7e" # Store my home routers mac address in homeRouterMac.
gatewayRouter=`/usr/sbin/arp -a`
# This if statement will search your gateway router for the mac address you have in the variable homeRouterMacAddress
if `echo ${gatewayRouter} | grep "${homeRouterMacAddress}" 1>/dev/null 2>&1`
then
echo "You are home"
else
echo "You are away"
fi
If you know that 0.0.0.0 is your expected output, and will be at the beginning of the line, you could use the following in your script:
IP=`netstat -rn | grep -e '^0\.0\.0\.0' | cut -d' ' -f2`
then reference the variable ${IP}.
It would be better to use awk instead of cut here... i.e.:
IP=`netstat -rn | grep -e '^0\.0\.0\.0' | awk '{print $2}'`
use command below:
route -n | grep '^0\.0\.\0\.0[ \t]\+[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*[ \t]\+0\.0\.0\.0[ \t]\+[^ \t]*G[^ \t]*[ \t]' | awk '{print $2}'
/sbin/route |egrep "^default" |cut -d' ' -f2-12 #and 'cut' to taste...
To get the NIC name that it's the default gateway use this command:
netstat -rn | grep UG | awk '{print $8}'

Resources