1

I'm trying to execute a command and then display its return code if it failed:

if ! /bin/false
then
   tee >(mail -s "failed" $USER) <<EOF
     Failed with code $?
EOF
fi

The above always echo's '0' for me, but I'm expecting to see '1'.

The following works, but it is not as simple and also doesn't play well with set -o errexit.

/bin/false
ret=$?
if [ $ret -ne 0 ]
then
   tee >(mail -s "failed" $USER) <<EOF
     Failed with code $ret
EOF
fi
4

2 回答 2

2

我会建议这种方法:

/bin/false || echo "Failed, return code = $?"
于 2013-07-24T18:07:28.277 回答
2

您的初始测试有缺陷。

尝试

if /bin/false ;then 
   echo status was $?
else
   echo "failed with status = $?"
fi

输出

failed with status = 1

要隔离使用真假,在cmd线上试试这些

 /bin/true ; echo $?; /bin/false; echo $? ; ! /bin/false; echo $?

输出

0
1
0

IHTH

于 2013-07-24T16:41:58.167 回答