Bash- Determine what interface is online

Hey guys, I want to use a a quick bash script/command to determine what network interface is connected to the internet so I can pipe it out to become a variable, in order so the user does not have to manually type it in each time or have to 'hardcode' the variable into the script.

I know about checking ifconfig etc of course, just looking for another way.

Many thanks and apologies for the kinda double post!

For LINUX, if you don't have to know the IP addresses of the interfaces, but just to enquire the status, mii-tool / ethtool also work. These commands might require root privilege to execute.

ip route get 8.8.8.8
8.8.8.8 via 192.168.10.1 dev eth0  src 192.168.10.33
    cache

This tests what route is used to connect to a public IP, like this Google DNS IP

gawk version (rs limitation)

ip route get 8.8.8.8 | awk 'NR==2 {print $1}' RS="dev"
eth0

You need to find the word after dev, and this can vary on the line, depending if computer is behind a firewall/router, or connected directly on the net.

EDIT: a more portable version

ip route get 8.8.8.8 | awk -F"dev " 'NR==1 {split($2,a," ");print a[1]}'

Which interface is connected to the internet is a routing thing:

Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
172.16.0.2      0.0.0.0         255.255.255.255 UH    0      0        0 tun0
192.168.0.0     0.0.0.0         255.255.255.0   U     0      0        0 lan
172.16.0.0      172.16.0.2      255.255.0.0     UG    0      0        0 tun0
127.0.0.0       0.0.0.0         255.0.0.0       U     0      0        0 lo
0.0.0.0         192.168.0.1     0.0.0.0         UG    0      0        0 lan

So, to always grab the catch-all default gateway:

$ /sbin/route -n | awk '/0\.0\.0\.0/ && /UG/ { print $NF ; exit }'

lan

$

This does not work on my VPS server.
It gives:

route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         0.0.0.0         0.0.0.0         U     0      0        0 venet0

This works fine

ip route get 8.8.8.8
8.8.8.8 dev venet0  src 32.244.0.10
    cache  ipid 0x2868 mtu 1500 advmss 1460 hoplimit 64

ip route get 8.8.8.8 | awk -F"dev " 'NR==1 {split($2,a," ");print a[1]}'
venet0

A default route can work without UG? Must be bridged... That makes my program even simpler though!

$ /sbin/route -n | awk '($1 == "0.0.0.0") { print $NF ; exit }'

lan

$

Spot on, problem solved, cheers guys.