Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (2024)

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

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.

Practice Files of Bash If Statement With Multiple Conditions

Table of Contents

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 truefi

Or,

if [ condition1 ] || [ condition2 ]; then#Code to execute if at least one condition is truefi

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 variablevalue=20#Checking if a number is within a specified rangeif [ "$value" -lt 35 -a "$value" -gt 18 ]; thenecho "Number $value is within 18 and 35."fi

EXPLANATION

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.

Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (2)

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/bashread -p "Enter your favorite color: " color#Checking if the entered color matches with the conditionif [ "$color" = "Black" ] || [ "$color" = "Blue" ] || [ "$color" = "White" ]; thenecho "Valid color entered."fi

EXPLANATION

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.’.

Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (3)

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 variablesclass="8"age=14#Checking if two conditions are metif [[ "$class" -le 10 && "$age" -ge 10 ]]; thenecho "Two conditions are met."fi

EXPLANATION

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.’.

Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (4)

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/bashread -p "Enter a filename: " filename#Checking if one condition is metif [[ "${filename##*.}" = "txt" ]] || [[ "${filename##*.}" = "conf" ]]; thenecho "One extension is found."fi

EXPLANATION

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.

Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (5)

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 variablescondition1="-f /home/nadiba/to/local.txt" #Providing information in /path/to/file_namecondition2="-d /home/nadiba/to/Desktop" #Providing information in /path/to/directory#Checking if both conditions are metif [ "$condition1" ] && [ "$condition2" ]; thenecho "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/bashfile_check() {local file_name=$1if [ -e "$file_name" ]; thenecho "'$file_name' exists."if [ -f "$file_name" ]; thenecho "'$file_name' is a regular file."elif [ -d "$file_name" ]; thenecho "'$file_name' is a directory."elseecho "'$file_name' is a special file."fielseecho "'$file_name' does not exist."fi}#Calling functionfile_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/bashread -p "Enter your mark: " markif [ "$mark" -ge 30 ]; thenecho "You have passed the exam."if [ "$mark" -ge 50 ]; thenecho "You have a good grade."elseecho "It is a bad grade."fielseecho "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/bashread -p "Enter a value from 1 to 5: " numbercase $number in1)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

Rate this post

Evaluate Multiple Conditions in Bash "If" Statement [2 Ways] - LinuxSimply (2024)
Top Articles
Latest Posts
Article information

Author: Ray Christiansen

Last Updated:

Views: 5723

Rating: 4.9 / 5 (49 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.