How to use logical operators in if statements?

065

Using Logical Operators in If Statements

Logical operators are essential tools in shell scripting, allowing you to create complex conditional statements and control the flow of your script. In shell, the most commonly used logical operators are:

  • && (AND operator)
  • || (OR operator)
  • ! (NOT operator)

These operators can be used within if statements to combine multiple conditions and make more sophisticated decisions.

AND Operator (&&)

The AND operator && evaluates two or more conditions and returns true (0) if all the conditions are true, and false (non-zero) otherwise. Here's an example:

if [ "$var1" -eq 10 ] && [ "$var2" -gt 5 ]; then
    echo "Both conditions are true!"
else
    echo "At least one condition is false."
fi

In this example, the script will execute the then block only if both $var1 is equal to 10 and $var2 is greater than 5.

OR Operator (||)

The OR operator || evaluates two or more conditions and returns true (0) if at least one of the conditions is true, and false (non-zero) if all conditions are false. Here's an example:

if [ "$var1" -eq 10 ] || [ "$var2" -gt 5 ]; then
    echo "At least one condition is true!"
else
    echo "Both conditions are false."
fi

In this example, the script will execute the then block if either $var1 is equal to 10 or $var2 is greater than 5.

NOT Operator (!)

The NOT operator ! negates the result of a condition. It returns true (0) if the condition is false, and false (non-zero) if the condition is true. Here's an example:

if ! [ "$var1" -eq 10 ]; then
    echo "The condition is false."
else
    echo "The condition is true."
fi

In this example, the script will execute the then block if $var1 is not equal to 10.

Combining Operators

You can also combine multiple logical operators to create more complex conditions. Here's an example:

if [ "$var1" -eq 10 ] && [ "$var2" -gt 5 ] || [ "$var3" -lt 0 ]; then
    echo "At least one condition is true!"
else
    echo "All conditions are false."
fi

In this example, the script will execute the then block if either:

  1. $var1 is equal to 10 and $var2 is greater than 5, or
  2. $var3 is less than 0.

To help visualize the logical flow, here's a Mermaid diagram:

graph TD A[Start] --> B{$var1 == 10 && $var2 > 5} B -- True --> C{$var3 < 0} B -- False --> D[All conditions are false.] C -- True --> E[At least one condition is true!] C -- False --> D E --> F[End] D --> F

Using logical operators in if statements allows you to create more complex and powerful shell scripts, enabling you to make decisions based on multiple conditions. Remember, clear and well-documented code is essential for maintainability and collaboration, so be sure to add comments to explain the purpose and logic of your scripts.

0 Comments

no data
Be the first to share your comment!