jazzzz jazzzz - 17 days ago 7
Linux Question

why shell logical not in if condition test behave not as expected

in my shell:

if ! mycommand;then
echo "mycommand has 0 exit code"
else
echo "mycommand has non-zero exit code"
fi


why mycommand return 1 but echo "mycommand has 0 exit code"?

I changed code as following:

mycommand
ret=$?
if [ $ret -eq 0 ]; then
echo "mycommand has 0 exit code"
else
echo "mycommand has non-zero exit code"
fi


when mycommand return 1,echo "mycommand has non-zero exit code" as i expected

Answer

The if-block will be executed only if the test condition returns 0, meaning success. A nonzero value will be considered an error and the else-block will be executed.

if something; then
    echo "Command succeeded (exit code 0)"
else
    echo "Command failed (exit code $?)"
fi

So remove the ! in your first code block and you will get the desired behavior.

Further reading: Bash Guide for Beginners: Conditional statements

Comments