bashexit-codereturn-code

Bash if statement expression evaluates to FALSE but $? is 0, why?


The example below echoes 1, as expected:

test -f /usr/bin
echo "$?" #1

Why does the following example echo 0?

if [[ -f /usr/bin ]]; then
    echo "Inside if statement" # This line is never executed    
fi
echo "$?" #0

I know that the $?evaluates to the returned value of the last executed command. In my understanding, the last executed command is test, that is implicitly called by the if statement, since the condition evaluates to false it should return 1, but when I execute it, it returns 0. Can anybody explain why the behavior is different than when test is executed directly (like in the first example)?


Solution

  • According to man bash:

    • if list; then list; [ elif list; then list; ] ... [ else list; ] fi

      The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.