BASH 语法错误 - [ : missing `]'

标签 bash shell sh

我是 Bash 编程的新手,可能真的很傻。

基本上我正在编写一段脚本,它将对我传入的 IP 地址执行 ping 操作,它将从中获取传输的数据包,并根据丢失的数据包数量返回错误或通过消息。

但是,每当我从终端运行脚本时,我都会收到消息 -

./ipGatewayCheck.sh:第 13 行:[: missing]'`

这是我的代码:

#!/bin/bash

healthy_status=0

warning_status=10

critical_status=100

for gateway in $@

do
RESULT=`ping -q -c 10 $gateway | grep 'packets transmitted' | awk '{print $6}' | tr -d "%"`
echo "$RESULT"
if [ $RESULT -eq $healthy_status ]; then
  echo "No Issue - IP Address is pinging"
elif [ $RESULT -ge $warning_status && -le $critical_status ]; then
  echo "Warning - Issue with packet loss on this IP Address"
elif [ $RESULT -eq $critical_status ]; then
  echo "Critical - 100% packet loss on this IP Address"
fi

done

如有任何帮助,我们将不胜感激。

最佳答案

您需要使用 [[]] 才能在方括号内使用 &&:

if [[ "$RESULT" -eq "$healthy_status" ]]; then
  echo "No Issue - IP Address is pinging"
elif [[ "$RESULT" -ge "$warning_status" && "$RESULT" -le "$critical_status" ]]; then
  echo "Warning - Issue with packet loss on this IP Address"
elif [[ "$RESULT" -eq "$critical_status" ]]; then
  echo "Critical - 100% packet loss on this IP Address"
fi

或者,您也可以在 BASH 中使用 (()):

if (( RESULT == healthy_status )); then
  echo "No Issue - IP Address is pinging"
elif (( RESULT == warning_status && RESULT < critical_status )); then
  echo "Warning - Issue with packet loss on this IP Address"
elif (( RESULT == critical_status )); then
  echo "Critical - 100% packet loss on this IP Address"
fi

关于BASH 语法错误 - [ : missing `]' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25991281/

相关文章:

linux - 如何遍历 .txt 并将每行的值用作变量 Linux Shell

python - 使用python获取Linux中所有已挂载的文件系统的列表

android - 从命令行运行 Robotium 测试套件

bash - 如何在 shell 中按周和按月扩展日期?

bash - 将 bash time 命令的输出加载到变量

在 Bitbucket 中使用预接收 Hook 时无法访问 Git 对象

linux - 自动应答 bash 脚本提示

linux - 如何在shell中逐行获取 `ps`的输出

bash - sed 在匹配单行字符串后追加多行字符串

bash - 从 shell 脚本执行 Maven 任务并获取错误代码