在现有脚本之前检查if语句中的退出代码

时间:2013-08-23 02:16:18

标签: bash

我想在现有脚本

之前检查第二个条件的退出代码
if [ -f "/var/lock/myproc/agentlock" ] && \
   [ $(ps ax | grep "myproc" | grep -v "grep" | awk '{print $1}' | xargs kill -9) ]; then

 echo "Exiting without running the rest of the script" | sendmail $myemail
 exit

fi

如果第二个命令的退出状态为非零,我想exit脚本。

1 个答案:

答案 0 :(得分:0)

你的意思是?

sendmail $myemail || exit # will exit if sendmail exit status is non-zero

很可能您想引用$myemail,如此:sendmail "$myemail"。这样可以防止bash globbing搞砸你的电子邮件。

如您所见,您可以使用&&检查零退出代码,||检查非零。

此外,您可以使用&& ||技巧编写简短的if语句:

[[ 'hello' == 'world' ]] && echo yes || echo no

如果您想否定某个条件,请使用! 像这样:

if [ firstcondition ] && ! [ secondcondition ]; then

表示''如果第一个条件为真且第二个条件不成立''

相关问题