2

I follow this post How to declare and use boolean variables in shell script?

and developed a simple shell script

#!/bin/sh                                                                                                                                                                                                   
a=false
if [[ $a ]];
then
    echo "a is true"
else
    echo "a is false"
fi

The output is

a is true

What is wrong?

1
  • 1
    if [[ $a ]] is not one of the options listed in any of the answers of the question you linked. Commented Jul 12, 2017 at 13:54

3 Answers 3

3

This doesn't work since [[ only tests if the variable is empty.
You need write:

if [[ $a = true ]];

instead of only

if [[ $a ]];
1

You need to check if the value equals true, not just whether the variable is set or not. Try the following:

if [[ $a = true ]];
1

Note that true and false are actually builtin commands in bash, so you can omit the conditional brackets and just do:

if $a; 

Update: after reading this excellent answer, I rescind this advice.


The reason if [[ $a ]] doesn't work like you expect is that when then [[ command receives only a single argument (aside from the closing ]]), the return value is success if the argument is non-empty. Clearly the string "false" is not the empty string. See https://www.gnu.org/software/bash/manual/bashref.html#Conditional-Constructs and https://www.gnu.org/software/bash/manual/bashref.html#Bash-Conditional-Expressions

Not the answer you're looking for? Browse other questions tagged or ask your own question.