FUNDAMENTALS A Complete Guide for Beginners
Including multiple conditions within an if statement in Bash refers to evaluating several criteria simultaneously by combining them with logical operators AND and OR within a single if block. You can either use the single square brackets “[ ]” i.e. equivalent test operator or double square brackets “[[ ]]” with extended functionality to encapsulate all the conditions and perform a complex conditional check.
In this article, I will exemplify 2 ways to evaluate multiple conditions within an ‘if’ condition in Bash.
What is Compound “If” in Bash?
In Bash scripting, ‘compound if’ is a statement that includes multiple conditions within an ‘if’ statement. It uses the logical operators AND, OR, and compound conditionals all together.
This is useful when you have to execute a specific block of code based on the number of satisfied conditions. The basic structure of a ‘compound if’ statement is as follows:
if [ condition1 ] && [ condition2 ]; then
#Code to execute if both conditions are true
fi
Or,
if [ condition1 ] || [ condition2 ]; then
#Code to execute if at least one condition is true
fi
2 Methods to Use Multiple Conditions in Bash “If” Statement
To check multiple conditions in a Bash if statement, you can employ both [ ]
and [[ ]]
constructs. The following is a description of how you can assess multiple conditions by combining them either using a single construct or using individual structures in Bash ‘if’ statements.
1. Using Single Square Brackets “[ ]”
In Bash scripting, the single square brackets [ ]
are considered as the equivalent test command that evaluates multiple conditions within an ‘if’ statement. In this case, the logical operators -a
and -o
can be used to combine all the conditions within a conditional expression where -a
is a logical AND and -o
is a logical OR.
To evaluate multiple conditions using -a
and -o
within one test alias, use the syntaxes as follows:
if [ CONDITION1 -a CONDITION2 ]; #True if both CONDITION1 and CONDITION2 are true.
if [ CONDITION1 -o CONDITION2 ]; #True if either CONDITION1 or CONDITION2 is true.
Here’s an example:
#!/bin/bash
#Defining a variable
value=20
#Checking if a number is within a specified range
if [ "$value" -lt 35 -a "$value" -gt 18 ]; then
echo "Number $value is within 18 and 35."
fi
In the script, if [ "$value" -lt 35 -a "$value" -gt 18 ];
checks if the defined value is less than 35
and greater than 18
. If both conditions are satisfied, the script returns a true expression.
From the above image, you can see that multiple conditions are satisfied using -a
within the “[ ]” construct.
Individual “[ ]” Construct for Each Condition
To evaluate multiple conditions within individual single square brackets [ ]
, use the syntaxes if [ CONDITION1 ] && [ CONDITION2 ];
and if [ CONDITION1 ] || [ CONDITION2 ];
.
Following is an example indicating the usage of individual single square brackets to handle multiple conditions:
#!/bin/bash
read -p "Enter your favorite color: " color
#Checking if the entered color matches with the condition
if [ "$color" = "Black" ] || [ "$color" = "Blue" ] || [ "$color" = "White" ]; then
echo "Valid color entered."
fi
Here, the if statement validates whether the entered color matches with any of the specified colors (Black, Blue or White). If any of the conditions becomes true, it prints ‘Valid color entered.’.
The above snapshot is a clear demonstration of multiple conditional checks using individual “[ ]” with “||”.
2. Using Double Square Brackets “[[ ]]”
Using double square brackets [[ ]]
with &&
(logical AND) and ||
(logical OR) helps in assessing multiple conditions within an ‘if’ statement.
To evaluate multiple conditions combined by &&
and ||
within one [[ ]]
construct, use the syntaxes below:
if [[ CONDITION1 && CONDITION2 ]]; #True if both CONDITION1 and CONDITION2 are true.
if [[ CONDITION1 || CONDITION2 ]]; #True if either CONDITION1 or CONDITION2 is true.
Look into the following example:
#!/bin/bash
#Defining two variables
class="8"
age=14
#Checking if two conditions are met
if [[ "$class" -le 10 && "$age" -ge 10 ]]; then
echo "Two conditions are met."
fi
Here, if [[ "$class" -le 10 && "$age" -ge 10 ]];
checks if the defined variable class is less than 10 and the variable age is greater than 10. If both conditions are met, the script displays ‘Two conditions are met.’.
This image states two conditional checks using “[[ ]]” with “&&” where two conditions were satisfied.
Individual “[[ ]]” Construct for Each Condition
To assess multiple conditions within an ‘if’ statement, use double square brackets notation individually combining them with &&
and ||
. For instance:
#!/bin/bash
read -p "Enter a filename: " filename
#Checking if one condition is met
if [[ "${filename##*.}" = "txt" ]] || [[ "${filename##*.}" = "conf" ]]; then
echo "One extension is found."
fi
In this script, the ‘if’ conditional checks whether the filename specified by the user has an extension of either txt
or conf
, where ${filename##*.}
extracts the extension from the filename using parameter expansion. If the filename’s extension matches any of these two conditions, the script returns a true expression.
This image illustrates the use of “[[ ]]” with “||” to evaluate multiple conditions.
Conclusion
To sum up, using multiple conditions within a Bash ‘if’ statement is a great way to test different scenarios of your scripts and make them more diverse and responsive.
People Also Ask
How can I check multiple conditions where at least one condition should be true?
You can use the OR (||
) operator to check multiple conditions where at least one condition should be true.
Can I use variables to store conditions in Bash if statements?
Yes, you can use variables to store conditions and evaluate them within Bash ‘if’ statements. For example:
#!/bin/bash
#Defining conditions in variables
condition1="-f /home/nadiba/to/local.txt" #Providing information in /path/to/file_name
condition2="-d /home/nadiba/to/Desktop" #Providing information in /path/to/directory
#Checking if both conditions are met
if [ "$condition1" ] && [ "$condition2" ]; then
echo "Both conditions are met.
fi
How do I ensure correct evaluation order when combining multiple conditions?
To ensure correct evaluation order when combining multiple conditions, you can use parentheses that explicitly help in preventing issues encountered with condition precedence.
Can I use functions to encapsulate complex conditions for readability?
Yes, you can use functions to encapsulate complex conditions for better code structure and readability. For example:
#!/bin/bash
file_check() {
local file_name=$1
if [ -e "$file_name" ]; then
echo "'$file_name' exists."
if [ -f "$file_name" ]; then
echo "'$file_name' is a regular file."
elif [ -d "$file_name" ]; then
echo "'$file_name' is a directory."
else
echo "'$file_name' is a special file."
fi
else
echo "'$file_name' does not exist."
fi
}
#Calling function
file_check "color.txt"
Can I nest multiple if statements to handle complex conditions?
Yes, you can nest if statements to handle complex conditions. However, excessive nesting can make it difficult to read and keep track of the code. You can use logical operators AND and OR instead. Let’s see an example:
#!/bin/bash
read -p "Enter your mark: " mark
if [ "$mark" -ge 30 ]; then
echo "You have passed the exam."
if [ "$mark" -ge 50 ]; then
echo "You have a good grade."
else
echo "It is a bad grade."
fi
else
echo "You have failed the exam."
fi
What’s the recommended approach for handling a large number of conditions?
When handling a large number of conditions, it’s recommended to use case statements or put the conditions in arrays to improve code maintainability. For example:
#!/bin/bash
read -p "Enter a value from 1 to 5: " number
case $number in
1)
echo "Valid number: One."
;;
2)
echo "Valid number: Two."
;;
3)
echo "Valid number: Three."
;;
4)
echo "Valid number: Four."
;;
5)
echo "Valid number: Five."
;;
*)
echo "Invalid number."
;;
esac
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]
- How to Use “OR”, “AND”, “NOT” in Bash If Statement [7 Examples]
- 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