Bash else /如果捕获退出状态

时间:2016-05-22 20:33:30

标签: bash macos shell unix

请帮我修理' elseif'在以下脚本中行,以便它可以捕获退出状态为零并继续而不会出错,因为我不知道构造它的正确语法。

我需要从以下命令中捕获零,但是在脚本的括号内。

softwareupdate -l 2>&1 | grep restart

我的剧本:

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH 
SWLOG=/var/log/swupdate.log

softwareupdate -l 2>&1 | grep "No new software available."

if [ $? -eq 0 ]

then
  echo "No new software was deemed to be available"

elif [ $(softwareupdate -l 2>&1 | grep restart & $? = 0) ]

then
  echo "RESTART will be needed"

else
  echo "Updates needed, but not restart"

fi

提前感谢您的建议和想法!

3 个答案:

答案 0 :(得分:2)

您可以使用grep -q并避免使用$?

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH 
SWLOG=/var/log/swupdate.log

if softwareupdate -l 2>&1 | grep -q "No new software available."
then
  echo "No new software was deemed to be available"    
elif softwareupdate -l 2>&1 | grep -q restart    
then
  echo "RESTART will be needed"    
else
  echo "Updates needed, but not restart"    
fi

答案 1 :(得分:2)

不要试图两次评估命令的输出,只需将输出发送到临时文件即可。

softwareupdate -l > temp.out 2>&1
grep "No new software available." temp.out > /dev/null
if [ $? -eq 0 ]
then
    echo "No new software was deemed to be available"
    exit
fi
grep "restart" temp.out > /dev/null
if [ $? -eq 0 ]
then
    echo "RESTART will be needed"
else
    echo "Updates needed, but not restart"
fi

答案 2 :(得分:0)

if softwareupdate -l 2>&1 | grep restart >/dev/null; then将完成这项工作。您不需要使用$?变量进行人工绕行。