Reputation: 926
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
Upvotes: 62
Views: 5233
Reputation: 780724
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.
This behavior is explained in the POSIX shell specification:
If there is no command name, but the command contained a command substitution, the command shall complete with the exit status of the last command substitution performed. Otherwise, the command shall complete with a zero exit status.
Upvotes: 81