Privacy Policy
© 2026 linux101.dev

Bash: Boolean Variables and Logical Operations

Bash does not have a native Boolean variable type. Commands communicate success or failure through exit statuses, and variables can store strings such as true and false that you compare explicitly.

Boolean Values in Bash

Using the true and false commands

 true
echo $?
false
echo $?

The true command exits with status 0, while false exits with a non-zero status. The special variable $? contains the exit status of the most recently run command.

Testing a Boolean Condition

Checking command success with if

 if [[ -f "config.txt" ]]; then
    echo "Configuration found"
else
    echo "Configuration is missing"
fi

A command or test can be used directly as the condition of an if statement. The then block runs when the command exits successfully, and the else block runs otherwise.

Boolean Variables

Storing and checking a Boolean-like value

 verbose=true
if [[ "$verbose" == true ]]; then
    echo "Verbose output enabled"
fi

A variable assigned true contains the string true; it is not a special Boolean value. Quote the expansion and compare it with [[ ... ]] when you need to check it.

Logical AND

Running a command only when both conditions succeed

 is_linux=true
is_ready=true
if [[ "$is_linux" == true && "$is_ready" == true ]]; then
    echo "Ready to continue"
fi

The && operator means AND. The combined condition is true only when both individual comparisons are true. Bash also uses && between commands to run the second command only if the first succeeds.

Logical OR

Accepting either of two conditions

 environment=staging
if [[ "$environment" == production || "$environment" == staging ]]; then
    echo "Known environment"
fi

The || operator means OR. The combined condition is true when at least one comparison is true. Between commands, || runs the second command only if the first command fails.

Logical NOT

Reversing a condition

 if [[ ! -d "backups" ]]; then
    echo "Backup directory does not exist"
fi

The ! operator negates a condition. A successful test becomes false, and a failed test becomes true.

Combining Commands

Using command exit statuses with logical operators

 mkdir -p "logs" && echo "Logs directory is ready"
[[ -f "app.conf" ]] || echo "Using default configuration"

Logical operators can connect commands as well as tests. This is useful for short success and fallback paths, but use an if statement when the logic needs multiple steps or detailed error handling.

Note: In Bash, exit status 0 means success or true, while a non-zero status means failure or false. This is the reverse of the common convention where zero represents false in other languages.
Desktop Ad Placeholder