【问题标题】:if loop within for loop in shell script not working如果shell脚本中for循环内的循环不起作用
【发布时间】:2013-11-11 20:07:48
【问题描述】:

我有以下 shell 脚本来发送电子邮件警报。当我只有 for 循环时,一切正常,但是当我尝试添加 if 条件时,它似乎不起作用并且每次都返回空消息正文。脚本中的 sn-p 如下:

for host in $servers
do
connections=`ssh $host "netstat -a | grep ES | wc -l"`
echo "$connections" >> debug.log
echo "$host" >> debug.log

if [$connections -gt 0]
then
echo "------------------------------------------------------------------" >> $emailmessage
echo "Host: $host needs to be checked" >> $emailmessage
echo "------------------------------------------------------------------" >> $emailmessage
echo "$connections" >> $emailmessage
else
echo "Everything is fine"
fi

done

当我尝试执行脚本时,我总是得到line 21: [49: command not found 错误。我尝试调试,但我发现我的脚本甚至没有进入 if 循环。

谁能告诉我我错过了什么?

提前致谢。

/rd

【问题讨论】:

  • 术语狡辩:if 语句不是循环。

标签: bash shell if-statement for-loop


【解决方案1】:

[] 周围应该有空格,也最好将变量放在引号中,因此将您的行更新为

...
if [ "$connections" -gt 0 ] ; 
then
...

【讨论】:

  • @rond 作为未来的提示,Shellcheck 会自动指出此类愚蠢的错误。
猜你喜欢
  • 2022-05-17
  • 1970-01-01
  • 2023-03-18
  • 2016-01-17
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-03-28
相关资源
最近更新 更多