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 loo
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