Jaquarh
Jaquarh

Reputation: 6693

How to retrieve only the IPV4 from ip addr in Linux

I am trying to pass the IPV4 for the tun0 interface into a script.

./start.sh `ip addr | grep tun0 | grep inet`

The issue I have is I cannot think how to separate this further to only get 10.10.14.252.

inet 10.10.14.252/23 scope global tun0

Any help appreciated to perhaps use sed to retrieve only the 10.10.14.252. The IPV4 is dynamic, the script can be executed on any environment and may not always start with 10.10

ip addr | grep tun0|grep inet|tr ' ' "\n"|grep 10.|tr '/' "\n"|grep 10

This works, its long but works. But am I guaranteed that the IPV4 will always start with 10?

Upvotes: 1

Views: 1622

Answers (4)

Cyrus
Cyrus

Reputation: 88756

I suggest:

ip -o -4 addr list tun0 | awk -F ' *|/' '{print $4}'

Upvotes: 4

James Brown
James Brown

Reputation: 37424

Using jq with ip -json:

$ ip -j -4 -o addr | jq -r '.[] | select(.addr_info[].dev=="tun0") | .addr_info[].local'

Upvotes: 3

markp-fuso
markp-fuso

Reputation: 34916

One sed idea using a capture group for the ip address:

$ ip addr | sed -En '/inet .* tun0/{s/^inet ([^ /]*).*/\1/p}'

NOTE: assumes the ip address follows immediately after the inet string and is followed by a space or a forward slash

For test purposes let's assume ip addr > ip.out generates:

$ cat ip.out
some stuff on line 1
inet 10.10.14.252/23 scope global tun0
some stuff on line 3

Simulating ip addr:

$ cat ip.out | sed -En '/inet .* tun0/{s/^inet ([^ /]*).*/\1/p}'
10.10.14.252

Upvotes: 1

tripleee
tripleee

Reputation: 189618

Try Awk.

ip addr |
awk '/inet/ && /tun0/ {
  ip = $2; sub(/\/.*/, "", ip); print ip }'

Generally, if you have a pipe with grep going into sed or Awk, get rid of the grep.

Upvotes: 2

Related Questions