Search code examples
bashpipeethernet

How to test if link is up in bash script


using this script I am trying to detect if there is a network link. I am failing in putting multiple commands in one line (ethtool...). What to do?

#!/bin/bash

COMMAND="( /sbin/ethtool eth0 ) | ( /bin/grep \"Link detected: yes\" ) | ( wc -l )"
ONLINE=eval $COMMAND 

if $ONLINE; then 
    echo "Online"
else
    echo "Not online"
fi

Solution

  • You simply need

    if /sbin/ethtool eth0 | grep -q "Link detected: yes"; then
        echo "Online"
    else
        echo "Not online"
    fi
    

    Also if you want to encapsulate checking, simply use a function:

    function check_eth {
        set -o pipefail # optional.
        /sbin/ethtool "$1" | grep -q "Link detected: yes"
    }
    
    if check_eth eth0; then
        echo "Online"
    else
        echo "Not online"
    fi
    

    How it works: if simply interprets a command in front of it and check if the return value of $? is 0. grep returns 0 when it finds a match on its search. And so because of this you don't need to use wc and compare its output to 1.