If block always goes to else in Bash

旧时模样 提交于 2021-02-16 13:53:09

问题


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:

  1. if [ $? -eq 5 ]
  2. if [ $? -eq "5" ]
  3. if [ $? == 5 ]
  4. if [ $? == "5" ]
  5. if [[ $? -eq 5 ]]
  6. if [[ $? -eq "5" ]]
  7. if [[ $? == "5" ]]
  8. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!