在 if
语句中检查
exit status以回显特定输出的最佳方法是什么?
我在想它是:
if [ $? -eq 1 ]
then
echo "blah blah blah"
fi
我还遇到的问题是
exit
语句在 if
语句之前,仅仅是因为它必须具有该退出代码。另外,我知道我做错了什么,因为退出显然会退出程序。
运行的每个命令都有一个退出状态。
该检查正在查看在该行运行之前最近完成的命令的退出状态。
如果您希望 your 脚本在该测试返回 true 时退出(前一个命令失败),那么您可以将
exit 1
(或其他)放在 if
块内,在 echo
之后。
话虽如此,如果您正在运行命令并想测试其输出,使用以下命令通常更直接。
if some_command; then
echo command returned true
else
echo command returned some error
fi
或者使用
!
来否定
if ! some_command; then
echo command returned some error
else
echo command returned true
fi
请注意,尽管这些都不关心错误代码是什么。如果您知道自己只关心特定的错误代码,那么您需要手动检查
$?
。
注意退出代码 != 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
显式
if
声明的替代方案
最低限度:
test $? -eq 0 || echo "something bad happened"
完成:
EXITCODE=$?
test $EXITCODE -eq 0 && echo "something good happened" || echo "something bad happened";
exit $EXITCODE
$?
是一个与其他任何参数一样的参数。您可以在最终调用 exit
. 之前保存它的值以供使用
exit_status=$?
if [ $exit_status -eq 1 ]; then
echo "blah blah blah"
fi
exit $exit_status
作为记录,如果脚本使用
set -e
(或 #!/bin/bash -e
)运行,因此您不能直接检查 $?
(因为脚本会在任何非零的返回码处终止),但想要处理特定的代码,@gboffis 评论很棒:
/some/command || error_code=$?
if [ "${error_code}" -eq 2 ]; then
...
只是添加到有用和详细的answer:
如果你必须明确地检查退出代码,最好使用算术运算符,
(( ... ))
,这样:
run_some_command
(($? != 0)) && { printf '%s\n' "Command exited with non-zero"; exit 1; }
或者,使用
case
语句:
run_some_command; ec=$? # grab the exit code into a variable so that it can
# be reused later, without the fear of being overwritten
case $ec in
0) ;;
1) printf '%s\n' "Command exited with non-zero"; exit 1;;
*) do_something_else;;
esac
Bash 中错误处理的相关回答:
如果你正在编写一个函数——这总是首选——你可以像这样propagate错误:
function()
{
if <command>; then
echo worked
else
return
fi
}
现在,调用者可以像预期的那样做像
function && next
这样的事情了!如果您在 if
块等中有很多事情要做,这将很有用(否则会有一行)。可以使用 false
命令轻松测试它。
使用 Z shell (
zsh
) 你可以简单地使用:
if [[ $(false)? -eq 1 ]]; then echo "yes" ;fi
当使用 Bash 并且
set -e
开启时,您可以使用:
false || exit_code=$?
if [[ ${exit_code} -ne 0 ]]; then echo ${exit_code}; fi
这可能只在一组有限的用例中有用,当我需要捕获命令的输出并在退出代码报告出现问题时将其写入日志文件时,我专门使用它。
RESULT=$(my_command_that_might_fail)
if (exit $?)
then
echo "everything went fine."
else
echo "ERROR: $RESULT" >> my_logfile.txt
fi
你可以只添加这个 if 语句:
if [ $? -ne 0 ];
then
echo 'The previous command was not executed successfully';
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
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
我错过了最简单的解决方案,就是使用
&&
运算符:
command --with parameters && echo "Command completed succesfully"
-- 假设
command
成功时返回 0,失败时返回非零,正如 Bash 所期望的那样(这与许多编程语言相反!)
||
运算符可用于失败:
commamnd --with parameters || echo "Command failed"