in Programming by (9.9k points)
0 like 0 dislike
286 views

How can I declare and use boolean type variables in a shell script (bash) in Linux console/terminal?


true and false bash

1 Answer

0 like 0 dislike
by (9.9k points)

You can declare and use boolean type variables somthing like this:

Declaration boolean variable:

boolVar=true

Check boolean variable in if-else operator:

if [ "$boolVar" = true ]

Full solution:

var=true
if [ "$var" = true ]; then
    echo 'Var is true!'
fi

Or without brackets:

var=true
if $var ; then
    echo 'Var is true!'
fi
var=false
if [ $var ]; then
  echo "This won't print, var is false!"
fi

Here are ways I recommend you check your boolean type variables. They work as expected.

bool=true

if [ "$bool" = true ]; then
if [ "$bool" = "true" ]; then

if [[ "$bool" = true ]]; then
if [[ "$bool" = "true" ]]; then
if [[ "$bool" == true ]]; then
if [[ "$bool" == "true" ]]; then

if test "$bool" = true; then
if test "$bool" = "true"; then

They're all pretty much equivalent. You'll have to type a few more keystrokes than the approaches in the other answers, but your code will be more defensive.

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.