【问题标题】:BASH use of variable to check active connectecion [duplicate]BASH使用变量检查活动连接[重复]
【发布时间】:2018-01-19 08:51:02
【问题描述】:

所以我有这个脚本(nettest.sh),代码如下:

#!/bin/bash

# Internet Check

linktest="$(ping -c 1 google.com)"
if [[ $linktest != *"not"* ]]; then
  echo -e " PASSED "
  echo -e " $linktest "
else
  echo -e " FAILED "
  echo -e " $linktest "
fi

ping失败的结果如下:

ping: google.com: Name or service not known

但这不起作用。当我有链接时,它会显示正确的消息。但是当链接断开时,它会一直显示 PASSED 消息并显示失败的 ping 消息。

有什么想法吗? (使用 Debian/Kali)

【问题讨论】:

    标签: linux string bash variables debian


    【解决方案1】:

    您的尝试不起作用的原因是因为ping 在失败时写入stderr$(...) 没有捕获到, 所以linktest 是空的。

    如果你把这行改成这样,你可以让它捕获stderr

    linktest=$(ping -c 1 google.com 2>&1)
    

    但实际上,不是解析输出,而是 最好直接使用ping的退出代码, 例如:

    if ping -c 1 google.com; then
      echo " PASSED "
    else
      echo " FAILED "
    fi
    

    您可能还想完全禁止来自ping 的所有输出:

    if ping -c 1 google.com &>/dev/null; then
    

    【讨论】:

    • 谢谢 janos,这帮助我理解了脚本中的一些内容。它正在 100% 工作。
    猜你喜欢
    • 2012-12-28
    • 2012-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2012-06-01
    相关资源
    最近更新 更多