Linux bash 用于检查互联网连接的脚本无法正常工作

Linux bash script to check internet connection not working

我想在 raspberry pi 上使用 bash 脚本来检查互联网连接是否仍然存在。

我找到了这个我扩展的脚本:

#!/bin/bash

# I do not work properly
if [[ "$(ping -c 1 8.8.8.8 | grep 'Network is unreachable' )" != "" ]]; then
    echo "Network isn't present"
    sudo shutdown -r 0
    exit 1
fi

# I work properly
if [[ "$(ping -c 1 8.8.8.8 | grep '100% packet loss' )" != "" ]]; then
    echo "Internet isn't present"
    sudo shutdown -r 0
    exit 1
else
    echo "Internet is present"
    exit 0
fi

第二部分很好用,但是第一部分不行。

我拔下以太网电缆并收到类似 connect: Network is unreachable 的错误消息。所以正如预期的那样。但我不明白为什么我的脚本没有接收到它?我认为这与它是错误消息而不是输出有关。但我不知道如何调整我的脚本以从错误消息中获取 grep,假设这是正确的。

我找到了一种方法,可以通过使用这一行 ping -c 1 8.8.8.8 2> >(grep 'unreachable';) 来让 grep 注册输出。但是,这仍然会使我的脚本失败,因为该行的其余部分不再识别它。而且我也不完全理解 2> >() 的作用。

试试这个:

x=`ping -c1 google.com 2>&1 | grep failure`
if [ ! "$x" = "" ]; then
echo "Network isn't present"
sudo shutdown -r 0
exit 1
fi

或者对于你的脚本我会这样做:

if [[ "$(ping -c 1 8.8.8.8 | grep '100% packet loss' )" != "" ]]; then
  echo "Internet isn't present"
  sudo shutdown -r 0
  exit 1
elif [[ "$(ping -c 1 8.8.8.8 | grep 'packet loss' | grep -o "1[0-9][0-9]\+%")" != "" ]]; then
  echo "Network isn't present"
  sudo shutdown -r 0
  exit 1
else
  echo "Internet is present"
  exit 0
fi

但我建议改用 /sys/class/net

# Test for network conection
for interface in $(ls /sys/class/net/ | grep -v lo);do
if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1;fi;done
if ! [ $OnLine ]; then echo "Internet isn't present" > /dev/stderr;sudo shutdown -r 0; exit; fi

这里你真的不需要字符串比较:

ping命令在完成执行后给出适当的return代码。

所以,您可以使用类似的东西:

 function check_connectivity() {

    local test_ip
    local test_count

    test_ip="8.8.8.8"
    test_count=1

    if ping -c ${test_count} ${test_ip} > /dev/null; then
       echo "Have internet connectivity"
    else
       echo "Do not have connectivity"
    fi
 }

 check_connectivity

Returns 结果毫不拖延:

$ net lookup example.com

`Didn't find example.com#20`

$ net lookup example.com

`93.184.216.34`