问题
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
This part: echo "the return code:$?."
echoes this to the screen: the return code:4.
And it does not display WARNING
. It only displays ERROR
and then breaks the for
loop this code is contained in.
What am i doing wrong?
Here are the variations of the condition compare that i have tried resulting in the same issue:
if [ $? -eq 5 ]
if [ $? -eq "5" ]
if [ $? == 5 ]
if [ $? == "5" ]
if [[ $? -eq 5 ]]
if [[ $? -eq "5" ]]
if [[ $? == "5" ]]
if [[ $? == 5 ]]
回答1:
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.
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.
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
来源:https://stackoverflow.com/questions/13292185/if-block-always-goes-to-else-in-bash