如何在bash脚本中测试链接是否已启动

Rob*_*rtK 1 bash ethernet pipe

使用此脚本我试图检测是否有网络链接.我没有将多个命令放在一行(ethtool ...).该怎么办?

#!/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
Run Code Online (Sandbox Code Playgroud)

orm*_*aaj 6

您的脚本问题似乎已得到解答。在Linux下我会通过直接读取sysfs来实现这一点。

function ifup {
    if [[ ! -d /sys/class/net/${1} ]]; then
        printf 'No such interface: %s\n' "$1" >&2
        return 1
    else
        [[ $(</sys/class/net/${1}/operstate) == up ]]
    fi
}

if ifup enp7s0; then
    echo Online
else
    echo 'Not online'
fi
Run Code Online (Sandbox Code Playgroud)

我的第二个选择可能是ip link

# Returns true if iface exists and is up, otherwise false.
function ifup {
    typeset output
    output=$(ip link show "$1" up) && [[ -n $output ]]
}

...
Run Code Online (Sandbox Code Playgroud)


kon*_*box 5

你只需要

if /sbin/ethtool eth0 | grep -q "Link detected: yes"; then
    echo "Online"
else
    echo "Not online"
fi
Run Code Online (Sandbox Code Playgroud)

此外,如果您想要封装检查,只需使用一个函数:

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
Run Code Online (Sandbox Code Playgroud)

工作原理:if只需解释前面的命令,并检查返回值是否$?0.当它在搜索中找到匹配时grep返回0.因此,您不需要使用wc和比较其输出1.