Bash – Difference between quoting variables in shell script “if” statements

bashquotingshellshell-script

What is the difference between these two Bash if-statements?
e.g.

if [ "$FOO" = "true" ]; then

vs

if [ $FOO = "true" ]; then

What is the difference? It seems that both statements work the same.

Best Answer

If the value of $FOO is a single word that doesn't contain a wildcard character \[*?, then the two are identical.

If $FOO is unassigned, or empty, or more than one word (i.e., contains whitespace or $IFS), then the unquoted version is a syntax error. If it happens to be just the right sequence of words (such as 0 -eq 0 -o false), the result could be arbitrary. Therefore, it is good practice to always quote variables in shell scripts.

Incidentally, "true" does not need to be quoted.

Related Question