Bash Scripting
  • scripting list
  • How to Make Bash Script Executable Using Chmod
  • Shell Script to Check Linux Server Health
  • How to Concatenate String Variables in Bash [Join Strings]
  • How to Do Bash Variable Substitution (Parameter Substitution)
  • Bash Parameter Expansion with Cheat Sheet
  • Bash getopts with Examples
  • How to Pass all Arguments in Bash Scripting
  • Bash Function Return Value
  • Bash Loop Through Lines in a File
  • Bash readarray with Examples
  • Bash let with Examples
  • Bash expr with Examples
  • Bash read password
  • Bash for Loop Range Variable
  • Bash Arrays Explained
  • Ways to Find Bash Array Length
  • Bash Split String by Delimiter
  • Bash if Options
  • Bash If Statements for String Comparison
  • Debugging Techniques for Bash Scripts
  • Determining if a Bash String is Empty
  • Bash if Statement with Multiple Conditions
  • Meaning of Shebang in Bash Scripts
  • How to Comment Code in Bash Script
  • How to Read CSV File in Bash
  • Bash Scripting: How to Check if File Exists
  • Bash If Else Statements: Examples and Syntax
  • Bash Scripting: How to Check if Directory Exists
  • Bash eval Command with Examples
  • How to Use Sleep Command in Bash Scripting
  • Bash Associative Arrays with Examples
  • Bash Script for Counting Lines in a File
  • How to Use While Loop in Bash for Efficient Scripting
  • Bash basename Command with Examples
  • How to Create Multiline Strings in Bash
  • How to Use Bash if With && Operator
  • 50 Bash Script Examples to Kickstart Your Learning
  • Case statement in Bash Shell Scripting
  • Trimming White Space in Bash
  • How to Extract Filename from Absolute Path in Bash
  • How to Get Directory Path in Bash
  • Extract Extension from File Path in Bash
  • Extract Filename without Extension from Full Path in Bash
  • Bash for Each File in a Directory
  • Bash for Loop with Array
  • Bash Continue – Using with for Loop
  • Bash Backticks vs Dollar Parentheses $()
  • How to Assign Variable in Bash
  • How to Assign Variable in Bash
  • Bash Division Explained
  • Bash Modulo (Division Remainder)
  • Bash While Read Line by Line
  • Bash shift Command
  • Bash Looping Through Array of Strings
  • Bash read Command with Examples
  • Bash Check Empty Array
  • Using Bash For Loops to Iterate Over a List of Strings
  • Bash Break – Using with For Loop
  • How to Use seq With for Loop in Bash
  • How to Use $@ in Bash Scripting
  • Get the Current Script Directory in Bash
Powered by GitBook
On this page
  • Using logical AND operator
  • What approach should we use?
  • Conclusion

How to Use Bash if With && Operator

PreviousHow to Create Multiline Strings in BashNext50 Bash Script Examples to Kickstart Your Learning

Last updated 1 year ago

It is highly likely that we will encounter an if condition while writing Bash scripts. The chances of having more than one possible flow of control, based on the conditions, is equally high. To prepare multiple conditions in the same "if- then- else" block, we might need to concatenate our statements. For this, we can use the and (&&) operator. By the end of this article, we will have understood how the Bash if statements work with the && operator.

Using logical AND operator

We might be required to join multiple expressions to develop the conditions for the if and else part of the code flow. For scenarios, involving more than 1 condition, Bash provides us with the logical AND operator. A logical operator connects two or more expressions in such a way that the value of the compound expression depends only on that of the original expressions and on the operator. The logical AND operator is represented using the && symbol.

Syntax

if [ EXPR1 ] && [ EXPR2 ]  && [ EXPRN ]
then    
    …
    …
else
    …
    …
fi

The if block of the code will execute only if all the expressions become true. Even if one fails, the else block will be called.

Example

#!/bin/bashnum=15if [ $num -gt 10 ] && [ $num -lt 20 ]then echo "Result is true. 10 < $num <20"else echo "Result is false."fi

Bash splits the expression into simpler ones and then evaluates each of them separately. It starts from left to right. Since we are using logical AND, the moment it comes across any condition which doesn’t hold true, it stops the execution straightaway. It then triggers the else block.

However, once all the conditions evaluate to true, it reassembles those expressions and executes the piece of code written within the then block. In this example the integer value is present with the variable num. The if condition can be considered as 2 separate if statements. The first one checks if the variable is greater than 10, which is true. The second checks if the number is less than 20, which is also true. As both are true and we have a logical AND, the result becomes true as well. This triggers the statements present inside the "then" block.

Using -a option with the if statement

Bash enables us to combine multiple conditions in one test alias using the -a (for and) option. In the previous case, where we surrounded our expressions in individual square braces. Here, we can concatenate multiple conditions, using the -a option, in the same square brackets.

Syntax

if [ EXPR1 -a EXPR2 ]	
then    
    …
    …
else
    …
    …
fi

Example

#!/bin/bashnum=15if [ $num -gt 10 -a $num -lt 20 ]then echo "Result is true. 10 < $num <20"else echo "Result is false."fi

Bash uses the same logic as we saw in the previous example where it splits the expression into simpler ones and then evaluates each of them separately. It then checks the operators to and it reassembles these expressions to compute the result of the original expression. This example can be considered as 2 separate if statements joined together with the -a flag. As both are true, the result is true and the "then" block executes.

Using double square brackets

Another way of having multiple conditions with the if statement is to use the double bracket ([[ ]]) notation.

Syntax

if [[ EXPR1 && EXPR2 ]]  
then    
    …
    …
else
    …
    …
fi

Example

#!/bin/bashnum=15if [[ $num -gt 10 && $num -lt 20 ]]then echo "Result is true. 10 < $num <20"else echo "Result is false."fi

This returns a status of 0 or 1 depending on the evaluation of the conditional expression. The expressions are made up of the same primaries used by the test alias we saw above. However, we need to use the && symbol for combining multiple expressions using logical AND. The && operators do not evaluate EXPR2 if EXPR1 is sufficient to determine the original expression's value. This example has 2 separate expressions, both true, joined by the logical AND. As the number 15 is greater than 10 and less than 15, the expression becomes true, triggering the then part of the program..

Using individual double square brackets

We can also use individual double square brackets to evaluate multiple conditions inside if and link them using the logical AND operator.

Syntax

if [[ EXPR1 ]] && [[ EXPR2 ]]
then    
    …
    …
else
    …
    …
fi

The if block of the code will execute only if EXPR1 as well as EXPR2 evaluates to true. If EXPR1 itself is false, EXPR2 won't be touched. This will make Bash run the else part of the code.

Example

#!/bin/bashnum=15if [[ $num -gt 10 ]] && [[ $num -lt 20 ]]then echo "Result is true. 10 < $num <20"else echo "Result is false."fi

We can consider double square brackets as an alternative to single brackets. However, unlike single brackets, it’s possible to have the comparison operators (>, < etc) with the double brackets. We should use the && operator for the logical AND operation. As is the case everywhere, Bash splits the expression into simpler ones and then evaluates each of them separately starting from the left. In the example it compares the number 15 with 10 to check if 15 is greater. Since it is true, it then compares if 15 is less than 20, which is also true. This makes the code reach the then part of the code and we get the statement that the result is true.

What approach should we use?

Now that we have seen so many ways of combining expressions with the && operator in the if statement, we might wonder which approach we should opt for. The arguments inside any of these techniques constitute an expression to evaluate. It will exit with a status of 0 if the expression is true, and a non-zero one if it's false.

However, if we go for the double brackets, we can safely use unquoted parameter expansions, unquoted parentheses and the < and the > symbols for string comparison. We have the flexibility of combining regular expressions, as well. If the environment is strictly POSIX compliant, the results might be misleading.

The bottom line is we are free to use whatever approach we like if we are on a relatively newer Linux version. It boils down to personal preference.

Conclusion

  • Bash can have multiple conditions with the if statement.

  • We have different ways of integrating the expressions with the if statement using the AND operator.

  • It's a personal choice to opt for the method we like. But it is a good practice to follow that everywhere so as not to confuse anyone who looks at our code.

bash if with -a option
if with double square brackets
bash script - if with && operator
bash if with individual double square brackets