user2872898
user2872898

Reputation: 121

If statement not evaluated correctly

I have a simple bash function that returns 3 numerical values: 0, 1, 2 When testing for the return value I get the correct value depending on the one returned from the function. # echo $? -> 0, 1, 2

However, when using an if-else statement the return value is not evaluate as I expected. For example when the function returns value = 2 in the if-else statement the elif [ $? -eq 1 ]; then is choosen

if [ "$?" -eq "0" ]; then
    echo "0"
elif [ "$?" -eq "1" ]; then
    echo "1"
elif [ "$?" -eq "2" ]; then
    echo "2"
else
    echo "Incorrect"
fi

Result: output is: 1 I expect: output is: 2

Any thoughts. Cheers, Roland

Upvotes: 0

Views: 126

Answers (1)

choroba
choroba

Reputation: 242383

By running [ "$?" -eq "0" ] you are changing the value of $?. If you want to compare it several times, store its value into a non-magical variable and compare it instead.

Other option is to use case:

case $? in
    (0) echo 0 ;;
    (1) echo 1 ;;
    (2) echo 2 ;;
    (*) echo Incorrect
esac

Upvotes: 3

Related Questions