存储执行失败的命令的输出



我正在尝试将命令的输出存储到脚本中的变量中,并根据存储在变量中的输出打印结果。

例如,在这个脚本中,我试图打印从lab.txt文件中读取的安装在几个系统上的代理的状态。如果状态与"isrunning"匹配,则打印"agent is installed"。

~]#  cat lab.txt
192.168.1.1
192.168.1.2

下面是脚本-

#!/bin/bash
while read host; do
status=$(ssh -n root@$host /opt/agent/bin/agent.sh status | awk 'NR==1{print $3 $4}')
if [ $status != isrunning ]
then
echo "agent is not installed"
else
echo "agent is installed"
fi
done < lab.txt

这里的问题是,如果命令返回错误,因为/opt/agent目录不存在于系统192.168.1.2上,则不会打印"agent is not installed"消息。这里有什么问题吗?

~]# ./script.sh
   root@192.168.1.1:
   agent is installed
   root@192.168.1.2:
   bash: /opt/agent/bin/agent.sh: No such file or directory
   ./script.sh: line 5: [: !=: unary operator expected
   agent is installed

$status未初始化,因此条件[ status != isrunning ]不满足。比如:

if [ "$status" != isrunning ]

应该解决这个问题,并消除unary operator expected的错误。

最新更新