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?

Viesturs
  • 123
  • 1
  • 9

3 Answers3

3

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

if [[ $a = true ]];

instead of only

if [[ $a ]];
NullDev
  • 6,739
  • 4
  • 30
  • 54
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 ]];
Secespitus
  • 710
  • 2
  • 14
  • 22
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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352