简体   繁体   English

shell脚本中的for循环中的if循环不起作用

[英]if loop within for loop in shell script not working

I have the following shell script in place to send out an email alert. 我已准备好以下外壳脚本来发送电子邮件警报。 When I only have the for loop everything works fine but when I try to add the if condition it does not seem to work and returns a null message body everytime. 当我只有for循环时,一切正常,但是当我尝试添加if条件时,它似乎不起作用,每次都返回空消息正文。 A snippet from the script is as below: 脚本的片段如下:

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

I always end up getting the line 21: [49: command not found error when i try to execute the script. 我总是最后得到第line 21: [49: command not found尝试执行脚本时line 21: [49: command not found错误。 I tried debugging but I figured out my script is not even getting inside the if loop. 我尝试调试,但发现自己的脚本甚至没有进入if循环。

Can someone please let me know what am I missing? 有人可以让我知道我在想什么吗?

Thanks in advance. 提前致谢。

/rd / RD

There should be space around [ and ] also its better to put variable in quotes, so update your line as []周围应该有空格,最好将变量放在引号中,因此将行更新为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM