The logical operators OR, AND, and NOT within an if statement in Bash indicate creating conditional logic that directs the script’s execution based on the conditionality. To visualize the different contexts of these three logical operators, you can utilize several conditional checks by combining or reversing Bash expressions.
In this article, I will introduce 7 practical examples of using OR, AND and NOT operators within an ‘if’ condition in Bash.
What Are the “OR”, “AND”, and “NOT” Operators in Bash?
OR, AND and NOT are the logical operators in Bash used to perform logical operations on conditional expressions. These operators provide flexibility in decision-making based on the conditional evaluation within scripts. Let’s look at a quick overview of all operators:
“OR” Operator in Bash
The OR (||) operator in Bash is a logical operator used to group multiple conditions inside an ‘if’ statement. It allows the execution of a command or a code block if at least one of the conditions is true.
The basic syntax for using the ‘OR’ operator within an ‘if’ condition in Bash is as follows:
if [ condition1 ] || [ condition2 ]; then
#Code to execute if either condition1 or condition2 is true
fi
If either of the conditions is true, the code block within the ‘if’ statement is executed. Otherwise, nothing is executed.
“AND” Operator in Bash
The AND operator within an ‘if’ condition is an operator that executes a code block only if all the specified conditions are true. It is represented as &&
and combines multiple conditions in Bash.
The syntax for using the ‘AND’ operator in an ‘if’ statement:
if [ condition1 ] && [ condition2 ]; then
#Code to execute if both condition1 and condition2 are true
fi
If both conditions are true, the ‘if’ block is executed. But if either of the conditions is false, nothing will be executed.
“NOT” Operator in Bash
The NOT operator within an ‘if’ statement negates the output of a condition. In Bash, it’s symbolized by !
.
Following is the syntax for using the ‘NOT’ operator in an ‘if’ condition:
if ! [ condition ]; then
#Code to execute if the condition is false
fi
7 Examples of Using “OR”, “AND”, “NOT” Operators With “if” Condition in Bash
OR, AND and NOT operators can be implemented in different scenarios across Bash scripting. Following are some examples dictating how these operators can be implemented within the ‘if’ conditional statement.
Example 1: Checking for File Existence or Readability Using “OR” Operator
To check whether a file exists or is readable, use the syntax if [ -f "msg.txt" ] || [ -r "msg.txt" ];
where the OR (||
) operator combines the two conditions and returns a true expression if either of the conditions is met. Let’s see an example:
#!/bin/bash
#Checking if a file exists or if it's readable
if [ -f "msg.txt" ] || [ -r "msg.txt" ]; then
echo "'msg.txt' exists or is readable."
fi
In the script, [ -f "msg.txt" ]
checks if the file msg.txt
exists and [ -r "msg.txt" ]
checks if the file is readable. The ‘if’ conditional using the || operator combines these two conditions. Hereafter, if any of the conditions becomes true, the script displays an output message.
From the above image, you can see that the file msg.txt
either exists or is readable in my system.
Example 2: Checking for Multiple Input Options Using “OR” Operator
To check multiple input options, use the OR (||
) operator within an if conditional. Following is an example of asking the user to enter an option and checking if it matches one of the given options.
#!/bin/bash
read -p "Select an option (A/B/C): " option
#Checking the input option
if [ "$option" = "A" ] || [ "$option" = "B" ] || [ "$option" = "C" ]; then
echo "Successful selection: $option"
fi
The ‘if’ statement checks if the value stored in the ‘option’ variable matches ‘A’, ‘B’, or ‘C’. using the ||
operator and the script echoes outputs based on the successful executions.
The above image illustrates successful validation for selecting either of the three specified options A, B and C.
Example 3: Validating Numeric Range Using “AND” Operator
Using the AND (&&
) operator within an if statement, you can perform a check on numeric value if it falls within a specified range. The below example symbolizes such a case where if [ "$number" -le 15 ] && [ "$number" -ge 9 ];
verifies if the entered value satisfies both lower and upper bound conditions simultaneously. If so, it will return True; otherwise, it will return nothing.
#!/bin/bash
read -p "Enter a number between 9 and 15: " number
#Checking if a number is within range
if [ "$number" -le 15 ] && [ "$number" -ge 9 ]; then
echo "Yes! $number is within the specified range."
fi
Here, The ‘if’ conditional using the &&
operator combines two conditions and checks if the number entered by the user is less than or equal to 15
and greater than or equal to 9
by using the syntaxes [ "$number" -le 15 ]
and [ "$number" -ge 9 ]
respectively. If both conditions are satisfied, the script executes a true expression and displays an output message.
As you can see from the image, the number 11 I have entered meets the specified conditions and is within the range between 9
and 15
.
Example 4: Checking for String Validation Using “AND” Operator
To perform a string validation test, you can combine multiple conditions using the AND (&&
) operator in Bash. Following is such a script where if [[ "$string" == *linux* && "${#string}" -le 15 ]];
validates whether the entered string satisfies both conditions simultaneously.
#!/bin/bash
read -p "Enter a string including 'linux' and containing maximum 15 characters: " string
#Checking for string validation
if [[ "$string" == *linux* && "${#string}" -le 15 ]]; then
echo "Valid String"
fi
Here, if [[ "$string" == *linux* && "${#string}" -le 15 ]];
checks if the entered string contains the substring linux
and if the length of the entered string is less than or equal to 15
. If both conditions are true, the script prints ‘Valid String’.
This image depicts that the string ‘linuxsimply’ I have entered contains the substring ‘linux’ and contains 11 characters which is less than 15.
Example 5: Checking for Directory Existence & Permissions Using “AND” Operator
If a directory exists and it has any user permissions can be checked concurrently within a Bash script by employing an AND (&&
) operator between each of the two conditional expressions. Following is an example where all the conditions must be satisfied to return a true result. If any of the given conditions are not met, it returns nothing.
#!/bin/bash
#Checking if a directory exists and has read, write and execute permissions
if [ -d "template" ] && [ -r "template" ] && [ -w "template" ] && [ -x "template" ]; then
echo "'template' exists and has read, write, and execute permissions"
fi
This script combines four conditions with &&
operator using syntaxes [ -d "template" ]
, [ -r "template" ]
, [ -w "template" ]
and [ -x "template" ]
to check if a directory named ‘template’ exists, if it is readable, writable and executable respectively. If all conditions are satisfied, it echoes an output.
From this image, you can see that the directory template
exists in my system and it has read, write and execution permissions as well.
Example 6: Checking for Non-existent File Using “NOT” Operator
The -f
flag within an ‘if’ statement in Bash is used to check whether a specific file path exists that corresponds to a regular file. The NOT (!
) operator literally reverses the output of a conditional expression within a script.
To check if a file does not exist, use the ! operator with the syntax [ -f "example.txt" ]
. Here’s a script:
#!/bin/bash
#Checking if a file does not exist
if ! [ -f "code.txt" ]; then
echo "'code.txt' does not exist."
fi
In the above script, if ! [ -f "example.txt" ];
checks if the file code.txt
does not exist and if the condition is satisfied, the script returns a true expression.
The above snapshot indicates that the file ‘code.txt’ does not exist in my system.
Example 7: Checking for Non-empty String Using “NOT” Operator
The -n
option in Bash is used to check whether a string has a length greater than zero i.e. the string is not empty. When using a NOT (!
) operator with the -n
option, it inverts its output and executes a reverse expression.
To check whether a string is not empty/null, use the syntax if ! [ -n "$input" ];
. For instance:
#!/bin/bash
#Defining a variable
var=""
#Checking if a string is not empty
if ! [ -n "$var" ]; then
echo "The string 'var' is not empty."
fi
Here, if ! [ -n "$input" ];
verifies if the given string has non-zero length i.e. it is not empty. If it is true, the script displays ‘The string is not empty.’.
In the above picture, you can see that the string var
has a length of non-zero i.e. it is not empty which implies the inverted result.
Conclusion
So far, you have encountered different types of examples of OR, AND and NOT operators within the Bash ‘if’ conditional. Just keep practicing these examples to make your Bash scripts more readable and easier to understand.
People Also Ask
Can ‘OR’, ‘AND’, and ‘NOT’ operators be used with string comparisons?
Yes, ‘OR’, ‘AND’, and ‘NOT’ operators can be used with string comparisons in Bash scripting. For instance:
#!/bin/bash
str="Hello"
#Checking for string comparison using ‘||’ operator
if [ "$str" == "Hello" ] || [ "$str" == "Linux" ]; then
echo "The string is either 'Hello' or 'Linux'."
fi
What happens if both conditions are false when using ‘||’?
When using the OR (||) operator within an ‘if’ conditional in Bash, if both conditions are false, the entire expression becomes False.
Can I combine ‘OR’, ‘AND’, and ‘NOT’ operators in a single Bash if statement?
Yes, you can combine ‘OR’, ‘AND’, and ‘NOT’ operators in a single Bash if statement to create complex conditional expressions. For example:
#!/bin/bash
var=15
if [ "$var" -gt 5 ] && [ "$var" -lt 39 ] || ! [ "$var" -eq 10 ]; then
echo "The value is greater than 5 and less than 39 or not equal to 10."
fi
Can ‘NOT’ (‘!’) operator be used multiple times consecutively within a single conditional expression in Bash?
Yes, the ‘NOT’ (‘!’) operator can be used multiple times consecutively within a single conditional expression in Bash.
What happens if I use ‘AND’ (‘&&’) and ‘OR’ (‘||’) together in a Bash if statement?
When you use ‘AND’ (‘&&’) and ‘OR’ (‘||’) together in a Bash if statement, it’s easy to get confused about the order of precedence. You can use parentheses in this case to apply the desired logic.
Can ‘OR’ (‘||’) and ‘AND’ (‘&&’) operators be nested within each other in Bash if statements?
Yes, ‘OR’ (‘||’) and ‘AND’ (‘&&’) operators can be nested within each other in Bash if statements.
In Bash scripting, are there alternative ways to achieve conditional branching without using ‘OR’ (‘||’), ‘AND’ (‘&&’), or ‘NOT’ (‘!’) operators?
Yes, in Bash scripting, there are alternative ways to achieve conditional branching without using ‘OR’ (‘||’), ‘AND’ (‘&&’), or ‘NOT’ (‘!’) operators such as using functions, nested if statement, case statement etc. For instance:
#!/bin/bash
number=30
if [ "$number" -lt 50 ]; then
if [ "$number" -gt 15 ]; then
echo "The number is less than 50 and greater than 15."
else
echo "The number is less than 50 but not greater than 15."
fi
else
echo "The number is not less than 50."
fi
Related Articles
- Mastering 10 Essential Options of If Statement in Bash
- How to Check a Boolean If True or False in Bash [Easy Guide]
- Bash Test Operations in ‘If’ Statement
- Check If a Variable is Empty/Null or Not in Bash [5 Methods]
- Check If a Variable is Set or Not in Bash [4 Methods]
- Check If Environment Variable Exists in Bash [6 Methods]
- Bash Modulo Operations in “If” Statement [4 Examples]
- Evaluate Multiple Conditions in Bash “If” Statement [2 Ways]
- Using Double Square Brackets “[[ ]]” in If Statement in Bash
- 6 Ways to Check If a File Exists or Not in Bash
- How to Check If a File is Empty in Bash [6 Methods]
- 7 Ways to Check If Directory Exists or Not in Bash
- Negate an “If” Condition in Bash [4 Examples]
- Check If Bash Command Fail or Succeed [Exit If Fail]
- How to Write If Statement in One Line? [2 Easy Ways]
- Different Loops with If Statements in Bash [5 Examples]
- How to Use Flags in Bash If Condition? [With Example]
- Learn to Compare Dates in Bash [4 Examples]
<< Go Back to If Statement in Bash | Bash Conditional Statements | Bash Scripting Tutorial
FUNDAMENTALS A Complete Guide for Beginners