Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

bash doesn't know boolean variables, nor does test (which is what gets called when you use [ ).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

The case answer (from @Jens) is safer and doesn't require a fork to test a simple variable. – Mark Lakata Sep 22, 2015 at 17:22

Note that the if $myVar; then ... ;fi construct has a security problem you might want to avoid with

case $myvar in
  (true)    echo "is true";;
  (false)   echo "is false";;
  (rm -rf*) echo "I just dodged a bullet";;

You might also want to rethink why if [ "$myvar" = "true" ] appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case solution is also handled without forks.

true and false are built-in commands in most shells. Invoking them is unlikely to require a fork() call. – Keith Thompson Sep 22, 2015 at 17:40 Calling which true in bash, zsh, ksh, dash, and fish, it seems that only zsh has true and false as built-ins. Seems like a sensible thing for shells to implement though! – Christopher Shroba Sep 13, 2020 at 13:39 don't use which -- that only searches the $PATH -- use type -a true -- true and false are builtin to bash and ksh and dash – glenn jackman Sep 13, 2020 at 20:15