bash "if [ false ];" returns true instead of false -- why?

tenmiles picture tenmiles · Oct 29, 2013 · Viewed 179k times · Source

Why does the following output True? #!/bin/sh

if [ false ]; then
    echo "True"
else
    echo "False"
fi

This will always output True even though the condition would seem to indicate otherwise. If I remove the brackets [] then it works, but I do not understand why.

Answer

chepner picture chepner · Oct 29, 2013

You are running the [ (aka test) command with the argument "false", not running the command false. Since "false" is a non-empty string, the test command always succeeds. To actually run the command, drop the [ command.

if false; then
   echo "True"
else
   echo "False"
fi