Skip to content

Instantly share code, notes, and snippets.

@adamjstewart
Last active July 30, 2016 14:10
Show Gist options
  • Save adamjstewart/7fc49b88b660d8504464c9d143043663 to your computer and use it in GitHub Desktop.
Save adamjstewart/7fc49b88b660d8504464c9d143043663 to your computer and use it in GitHub Desktop.
Bash boolean examples
#!/usr/bin/env bash
# Various methods of using Booleans in Bash
# Credit for most of these techniques comes from:
# http://stackoverflow.com/questions/2953646/
###########################################################
# Using the builtin 'true' and 'false' commands
###########################################################
# Most elegant solution, but has some pitfalls.
# The empty string and unset variables evaluate to true.
# Also opens up the possibility of shell injection.
foo=true
bar=false
if $foo && ! $bar
then
echo "True"
else
echo "False"
fi
if $bar || ! $foo
then
echo "True"
else
echo "False"
fi
###########################################################
# Using strings and checking for string equality
###########################################################
# Not as elegant, but safest and most POSIX compatible option.
# Can be any string, doesn't have to be true or false.
foo="true"
bar="false"
# POSIX compatible
if [ "$foo" = true -a ! "$bar" = true ]
then
echo "True"
else
echo "False"
fi
# Bash-ism
if [[ $bar == true || $foo != true ]]
then
echo "True"
else
echo "False"
fi
###########################################################
# Using 0 and 1 and evaluating arithmetic expressions
###########################################################
# Works, but can become very difficult to keep
# track of whether 0 or 1 is true or false.
# Similar to how C handles Booleans.
foo=1 # true
bar=0 # false
if ((foo && ! bar))
then
echo "True"
else
echo "False"
fi
if ((bar || ! foo))
then
echo "True"
else
echo "False"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment