Home > Software engineering >  Why does bash treat undefined symbols as true in an if statement?
Why does bash treat undefined symbols as true in an if statement?

Time:07-07

In the below simple example, if CONDITION is not set in the script, running the script prints "True". However one would expect it to print "False". What is the reason for this behavior?

# Set CONDITION by using true or false:
# CONDITION=true or false

if $CONDITION; then
    echo "True"
else
    echo "False"
fi

CodePudding user response:

The argument to if is a statement to execute, and its exit status is tested. If the exit status is 0 the condition is true and the statements in then are executed.

When $CONDITION isn't set, the statement is an empty statement, and empty statements always have a zero exit status, meaning success. So the if condition succeeds.

CodePudding user response:

What you are looking for is the test command... also known as the [ square bracket command...

if test "$CONDITION"
then
  echo true
fi

or..

if [ "$CONDITION" ]
then
  echo true
fi
  •  Tags:  
  • bash
  • Related