如果块总是在Bash中转到else [英] If block always goes to else in Bash
问题描述
下面的代码段在应放入 elif
时进入 else
语句.
The following segment of code goes to the else
statement when it should be going into the elif
.
#The following line returns 3, 4 or 5 as the exit code.
$BASH_EXEC adbE.sh "adb $ARGUMENT install $f"
echo "the return code:$?."
if [ $? -eq 5 ]
then
#do nothing, success
continue
elif [ $? -eq 4 ]
then
echo "WARNING"
else
echo "ERROR"
break
fi
此部分: echo返回代码:$?."
将其回显到屏幕:返回代码:4.
This part: echo "the return code:$?."
echoes this to the screen: the return code:4.
它不显示 WARNING
.它仅显示 ERROR
,然后中断包含此代码的 for
循环.
And it does not display WARNING
. It only displays ERROR
and then breaks the for
loop this code is contained in.
我在做什么错了?
这是我尝试导致相同问题的条件比较的变体:
Here are the variations of the condition compare that i have tried resulting in the same issue:
-
如果[$?-eq 5]
-
如果[$?-eq"5";]
-
如果[$?== 5]
-
如果[$?=="5";]
-
如果[[$?-eq 5]]
-
如果[[$?-eq"5";]]
-
如果[[$?=="5";]]
-
如果[[$?== 5]]
if [ $? -eq 5 ]
if [ $? -eq "5" ]
if [ $? == 5 ]
if [ $? == "5" ]
if [[ $? -eq 5 ]]
if [[ $? -eq "5" ]]
if [[ $? == "5" ]]
if [[ $? == 5 ]]
推荐答案
原因是 $?
是最后执行的命令的返回代码.您在 if
之前运行 echo
命令,因此您正在测试的是 echo
的返回码,它将始终是0.
The reason for this is that $?
is the return code for the last executed command. You are running an echo
command before the if
, so it is the return code of echo
that you are testing, which is always going to be 0.
在您的情况下,还存在另一个问题,因为您正在重新测试 elif
语句中的返回值.初始测试(即 [$?-eq 5]
)也会更改 $?
的值,因此重新测试将产生意外的结果.
Also, in your case, there is an additional problem caused by the fact that you are retesting the return value in the elif
statement. The initial test (i.e. [ $? -eq 5 ]
) will also change the value of $?
, so retesting it will give an unexpected result.
要解决此问题,请在执行 echo
之前保存以前的返回码,然后将保存的版本用于以后的所有测试:
To fix this situation, save the previous return code before doing the echo
, and then use the saved version for all future tests:
ret=$?
echo "the return code:${ret}."
if [ ${ret} -eq 5 ]
then
#do nothing, success
continue
elif [ ${ret} -eq 4 ]
then
echo "WARNING"
else
echo "ERROR"
break
fi
这篇关于如果块总是在Bash中转到else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!