为了回显特定的输出,在if语句中检查退出状态的最佳方法是什么?
我想的是:
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
我还遇到的问题是,退出语句是在if语句之前,因为它必须有退出代码。此外,我知道我做错了什么,因为退出显然会退出程序。
为了回显特定的输出,在if语句中检查退出状态的最佳方法是什么?
我想的是:
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
我还遇到的问题是,退出语句是在if语句之前,因为它必须有退出代码。此外,我知道我做错了什么,因为退出显然会退出程序。
当前回答
下面的测试脚本
简单的bash测试命令 多个测试命令 Bash测试命令包括管道:
if [[ $(echo -en "abc\n def" |grep -e "^abc") && ! $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
if [[ $(echo -en "abc\n def" |grep -e "^abc") && $(echo -en "abc\n def" |grep -e "^def") ]] ; then
echo "pipe true"
else
echo "pipe false"
fi
输出结果为:
pipe true
pipe false
其他回答
注意,退出代码!= 0用于报告错误。所以,最好这样做:
retVal=$?
if [ $retVal -ne 0 ]; then
echo "Error"
fi
exit $retVal
而不是
# will fail for error codes == 1
retVal=$?
if [ $retVal -eq 1 ]; then
echo "Error"
fi
exit $retVal
使用Z shell (zsh),你可以简单地使用:
if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi
当使用Bash并设置-e为on时,您可以使用:
false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi
你可以添加这个if语句:
if [ $? -ne 0 ];
then
echo 'The previous command was not executed successfully';
fi
如果你正在编写一个函数——这总是首选的——你可以像这样传播错误:
function()
{
if <command>; then
echo worked
else
return
fi
}
现在,调用者可以像预期的那样执行function && next !如果你在if块中有很多事情要做,这是很有用的(否则有一行程序)。使用false命令可以很容易地测试它。
这可能只在有限的用例集中有用,我特别在需要捕获命令的输出并在退出代码报告出错时将其写入日志文件时使用这种方法。
RESULT=$(my_command_that_might_fail)
if (exit $?)
then
echo "everything went fine."
else
echo "ERROR: $RESULT" >> my_logfile.txt
fi