Bash Boolean Operations

In Bash, boolean operations are used to evaluate logical conditions and perform logical operations. The commonly used boolean operators in Bash are:

  1. Logical AND (&&): The && operator returns true if both the left-hand side and the right-hand side conditions are true. Otherwise, it returns false. It short-circuits the evaluation, meaning that if the left-hand side condition is false, the right-hand side is not evaluated.
  2. Logical OR (||): The || operator returns true if either the left-hand side or the right-hand side condition is true. It returns false only if both conditions are false. Like &&, it also short-circuits the evaluation.
  3. Logical NOT (!): The ! operator negates the truth value of a condition. If the condition is true, ! returns false. If the condition is false, ! returns true.

Here’s an example that demonstrates the usage of boolean operations in Bash:


# Logical AND
if [ "$1" -gt 5 ] && [ "$1" -lt 10 ]; then
    echo "$1 is between 5 and 10."
    echo "$1 is not between 5 and 10."

# Logical OR
if [ "$2" == "open" ] || [ "$2" == "closed" ]; then
    echo "The door is $2."
    echo "The door status is unknown."

# Logical NOT
if ! [ -f "$3" ]; then
    echo "File $3 does not exist."
    echo "File $3 exists."

In this example, we use boolean operators to perform different logical checks:

  • The first if statement checks if the value of $1 is between 5 and 10 using the logical AND operator &&.
  • The second if statement checks if the value of $2 is either “open” or “closed” using the logical OR operator ||.
  • The third if statement checks if the file specified by $3 does not exist using the logical NOT operator !.

When you run this script with appropriate command-line arguments, it will output the corresponding messages based on the evaluation of boolean conditions.

Boolean operations in Bash allow you to combine and evaluate logical conditions to make decisions and control the flow of your script based on multiple conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *