如果条件更好,如何改善?

时间:2017-04-19 08:24:27

标签: bash shell if-statement conditional-statements

我必须在脚本中添加if条件。在这种情况下,脚本将在远程计算机上运行,​​如果该脚本的输出包含欲望模式/文本,则条件为真,否则为false。

脚本如下:

  

ssh autoengine@dell425srv "cd /net/dell425srv/dell425srv2/apps/;./check_status_splunkforwarder2.sh"

输出运行脚本后:

  

bash $ ssh autoengine @ dell425srv" cd / net / dell425srv / dell425srv2 / apps /   ; ./check_status_splunkforwarder2.sh" splunkd正在运行(PID:537)。   splunk助手正在运行(PID:538)。

如果条件为真则显示" splunkd正在运行"否则" splunkd没有运行"。

1 个答案:

答案 0 :(得分:0)

您可以直接使用grep的返回码,如下所示:

# Remote command in function (for readability only)
remote_command()
{
ssh autoengine@dell425srv "cd /net/dell425srv/dell425srv2/apps/;./check_status_splunkforwarder2.sh"
}

if
  remote_command | grep -q "splunkd is running"
then
  echo "splunkd is running"
else
  echo "splunkd is not running"
fi

您可以使用代码来区分失败的远程命令执行和失败的grep

return_code=0
output=$(remote_command) || return_code=$?

if
  ((return_code))
then
  echo "Remote command failed"
elif
  grep -q "splunkd is running" <<<"$output"
then
  echo "splunkd is running"
else
  echo "splunkd is not running"
fi