Toilal
Toilal

Reputation: 3409

Find gateway of an interface

For a bash integration, i need to retrieve the default gateway from an interface.

here is the output of the command route -n

Table de routage IP du noyau
Destination     Passerelle      Genmask         Indic Metric Ref    Use Iface
0.0.0.0         p.p.p.p         128.0.0.0       UG    0      0        0 tun0
0.0.0.0         x.x.x.x         0.0.0.0         UG    100    0        0 eth0
10.43.0.1       10.43.0.5       255.255.255.255 UGH   0      0        0 tun0
10.43.0.5       0.0.0.0         255.255.255.255 UH    0      0        0 tun0
y.y.y.y         x.x.x.x         255.255.255.255 UGH   0      0        0 eth0
x.x.x.0         0.0.0.0         255.255.255.0   U     0      0        0 eth0
128.0.0.0       10.43.0.5       128.0.0.0       UG    0      0        0 tun0

I try to capture gateway (Passerelle in French) for Iface tun0.

This regex is working on Rubular:

^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$

But this shell command doesn't work (no output):

route -n |egrep -oh '^[0\.]+\s+([\w\.]+)\s+.*UG.*tun0$'

Please, tell me why ?

Upvotes: 1

Views: 1485

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185560

Try doing this (only one pipe) :

route -n | 
    awk -viface=eth0 '{if ($1 == "0.0.0.0" && $8 == iface) {print $2;exit}}'

or even better :

ip route |
    awk -viface=eth0 '{
        if ($1 == "default" && $2 == "via" && $5 == iface) {print $3; exit}
    }'

Upvotes: 1

BeniBela
BeniBela

Reputation: 16927

Another option, without regex and awk:

route -n | grep -E "ppp0$" | tr -s ' ' | cut -f 2 -d ' '

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272677

Why not just use awk, rather than a grotesque regex? Something like:

route -n | grep -e 'UG.*tun0' | awk '{print $2}'

Disclaimer: I have not tested this, so there may be a typo...

Upvotes: 2

Related Questions