In Bash, you can declare a Boolean variable using the declare
or typeset
command, followed by the variable name and the value. For example, to declare a variable called “flag” and set it to true, you would use the following command:
flag=true
You can also use the -g
option to make the variable global and the -r
option to make the variable readonly.
declare -gr flag=true
You can use Boolean variables in shell scripts just like you would use any other variable. For example, you can use them in an if statement:
if [ "$flag" = true ]; then
echo "flag is true"
else
echo "flag is false"
fi
You can also use the &&
and ||
operators to chain commands together based on the value of a Boolean variable:
flag=true
$flag && echo "flag is true" || echo "flag is false"
You can also use the test
command or [ ]
to check the state of the variable
flag=true
if test $flag; then
echo "flag is true"
else
echo "flag is false"
fi
Please note that in bash, only the strings ‘true’ and ‘false’ are considered as boolean values, other strings or numbers will be treated as normal variables and will not work as expected.