Check whether network cable is plugged in without bringing interface up

ip link show , by default shows all the interfaces, use ip link show up to show only the running interfaces. You could use filters to get the difference.


Here is my script to update default routes based on the state of the connection in realtime. (runs in background) works with multiple interfaces, I define priorities in the /tmp/${iface}.metric files, the 'best' connected interface will be used to route default traffic.

#!/bin/sh

/sbin/ip monitor link | while read -r line
do
    iface=$(echo $line | sed -ne 's/[^ ]* \([^ ]*\): .* state \([^ ]*\).*/\1/p')
    state=$(echo $line | sed -ne 's/[^ ]* \([^ ]*\): .* state \([^ ]*\).*/\2/p')
    if [ "$iface" != "" ] ; then
        echo "$iface is $state"
        if [ -f /tmp/${iface}.metric ] ; then
                echo "updating default route for ${iface}"
                if [ "$state" = "DOWN" ] ; then
                        ip route del default dev "${iface}"
                else
                        ip route add default dev "${iface}" metric `cat /tmp/${iface}.metric`
                fi
        fi
    fi
done