Bash If Else Statements: Examples and Syntax

Conditional statements are one of the most essential constructs of any programming language. Bash supports using if…elif…else statements like in many other programming languages.

In this tutorial, we learn about bash if else statements with examples.

Bash If statements

Plain if statement is the most basic construct for specifying conditions in a Bash script.

It follows the syntax:

if [ condition ]; then
	statement
fi

Let’s take the following example to understand the working of if statements:

#!/bin/bash ## 1if [ 3 > 1 ]; then echo "1st if condition satisfied"fi ## 2if (( 4 / 2 < 2 )); then echo "2nd if condition satisfied"fi

Now, let’s observe the output on executing the script:

bash if statement example
  • In the first case, we see the script enters the execution block since condition 3>1 is satisfied.

  • In the second case, the condition 4/2 < 2 evaluates to false, hence the execution block is skipped.

How to specify conditions?

Bash provides us with a number of ways to specify conditions in the if statements. Let’s explore them in the next sections.

Single parentheses

Bash treats the single parentheses blocks `( <expr> )` as a subshell. When using the if statements with single parentheses blocks, the script execution is blocked until the subprocess terminates and the condition is evaluated using the exit status of the subprocess.

Let’s consider the following example:

#!/bin/bash ## 1if ( word="satifsied"; grep -q $word ifStatement.sh ); then echo "1st if condition satisfied"fi ## 2if ( word="satisfied"; grep -q $word ifStatement.sh ); then echo "2nd if condition satisfied"fi

In the script, we search for patterns using grep command in the if block.

Now, let’s execute the script and observe the output in both cases:

bash if single parentheses
  • In the first example, grep could not find the pattern and thus the if statement evaluates to false.

  • In the second example, grep finds the pattern and thus evaluates to true.

Double parentheses

Bash uses double parentheses expressions `(( <expr> ))` for arithmetic operations. When a double parenthesis is used inside an if block, Bash computes the expression using standard arithmetic principles and then applies conditional checks on the result.

If the result = 0, it evaluates to false. Else, it is true.

Let’s demonstrate this with the help of an example:

#!/bin/bash ## 1if (( 3+2 )); then echo "1st if condition satisfied"fi ## 2if (( 3-3 )); then echo "2nd if condition satisfied"fi

We have 2 if blocks, each with an arithmetic expression.

Executing the script:

bash if double parentheses
  • In the first condition, 3+2 ≠ 0, which evaluates to true, and the script executes the statements inside the if block.

  • In the second condition, 3-3 = 0, which evaluates to false.

Single bracket

In Bash scripting, single brackets `[ <expr> ]` are used to test conditions. When used inside an if block, they are used to evaluate the condition provided and determine whether to execute the code block inside the if statement.

Let’s check this with an example:

#!/bin/bash ## 1if [ -z $animal ]; then echo "1st if condition satisfied"fi ## 2animal="giraffe"if [ -z $animal ]; then echo "2nd if condition satisfied"fi

In the script, we have 2 if conditions checking if the variable animal is unset.

Let’s run the script and observe the output in both cases:

bash if single brackets
  • The first condition evaluates to true since the variable animal is not defined, hence the statements following the if block are executed.

  • In the second example, animal gets defined as “giraffe” and hence fails the if condition.

Double bracket

Double brackets `[[ <expr> ]]` are also used to test conditions. They are similar to single brackets but provide advanced functionality for pattern matching and logical operators.

Let’s take an example:

#!/bin/bash str="aabbcc123---"if [[ "$str" =~ [abc]+[123]+-* ]]; then echo "If condition satisfied"fi

In the example, we have a string that is equated against a regular expression.

Let’s observe the output by running the script:

bash if double brackets
  • The regex matches the string and hence the statements in the if block are executed.

Double brackets also allow using logical operators such as the logical AND ( && ), logical OR ( || ).

For example

#!/bin/bash str1="aabbcc123---"str2="1233aabbcc" ## 1pat="[abc]+[123]+-*"if [[ "$str1" =~ $pat && "$str2" =~ $pat ]]; then echo "1st if condition satisfied"fi ## 2if [[ "$str2" =~ $pat || "$str1" =~ $pat ]]; then echo "2nd if condition satisfied"fi

Invoking the script:

script output of  bash if logical operators
  • In the first case, the second expression evaluates to false hence the overall expression becomes false with && operator.

  • In the second case, the first expression evaluates to false, but the second expression is true, hence the overall expression becomes true with the || operator.

Bash If Else statements

The if block can be used to create a single conditional logic for the execution of some statements in a block. However, it doesn’t allow us to control the behavior of the script if the expression evaluates to false.

Else block uses the syntax:

if [ condition ]; then
	statements
else
      statements
fi

With an else block, we can specify what to execute if the expression is false.

Let’s see this with an example:

#!/bin/bash read -p "Enter the username: " usernameif [ $username == "john007" ]; then echo "Hello john007!"else echo "Invalid username entered"fi

In this example, we request input from the user and generate a customized greeting based on user inventory.

Running the script:

the output of Bash If Else statements script
  • When we enter “john008”, which is not in the user inventory, the script executes the statements in the else block and generates an invalid request error.

  • When we enter “john007”, the if condition evaluates to true and prints a greeting to the stdout.

Bash if…Elif…Else statements

If Else blocks are helpful for writing binary conditions. But, real scenarios often include multiple conditional blocks. This is where the Elif block comes in.

Here’s the syntax for using Elif blocks:

if [ condition ]; then
	statements
elif [ condition ];
      statements
elif [ condition ];
      statements
.
.
.
else 
	statements
fi

Extending the script from the previous example and adding more users to the inventory:

#!/bin/bash read -p "Enter the username: " usernameif [ $username == "john007" ]; then echo "Hello john007!"elif [ $username == "john008" ]; then echo "Hello john008!"elif [ $username == "john009" ]; then echo "Hello john009!"else echo "Invalid username entered"Fi

Let’s enter the username john008 and observe what happens now:

output of bash if…Elif…Else script
  • This time, we see the script recognizes john008 as a valid user.

Bash Nested If Else statements

Bash also supports writing multiple if else blocks in a nested fashion. This allows us to apply multiple conditional checks in conjunction. The execution of one if block is guarded by another if block.

Nested if blocks help in writing complex conditional logic in a more readable manner as compared to single if blocks.

Extending the script from the previous example to accept a password from the user:

#!/bin/bash read -p "Enter the username: " usernameif [ $username == "john007" ]; then read -sp "Enter the password: " password if [ $password == "pass1234" ]; then echo "Hello john007!" fielse echo "Invalid username entered"fi

The output of bash nested if script

The script only prints the message to the stdout if both the conditions evaluate to true, i.e. the username and password entered by the user match in the inventory.

Conclusion

  • Conditional statements are an important building block of a programming language. Bash supports conditional statements using if…elif…else blocks.

  • There are multiple methods to specify conditions in an if block.

  • Single parentheses `( )` in an if block can be used to execute statements in a subprocess and perform logical decisions based on the exit status of the subprocess.

  • Double parentheses `(( ))` are used to create conditional blocks using arithmetic expressions.

  • Single brackets `[ ]` are used to write test conditions and execute statements in the if block based on these test conditions.

  • Double brackets `[[ ]]` are an improvement over single brackets since they support pattern matching and the use of logical operators.

  • Like other programming languages, Bash also supports elif, and else blocks to create multiple conditional blocks in a script.

  • Nested if else blocks can also be used to write complex conditions. However, these must generally be avoided as a good programming practice.

Last updated