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
  • Bash If statements
  • Conclusion

Bash If Else Statements: Examples and Syntax

PreviousBash Scripting: How to Check if File ExistsNextBash Scripting: How to Check if Directory Exists

Last updated 1 year ago

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:

  • 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:

  • 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:

  • 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:

  • 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:

  • 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:

  • 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:

  • 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:

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

bash if single parentheses
bash if double brackets
script output of  bash if logical operators
bash if double parentheses
output of bash if…Elif…Else script
bash if statement example
bash if single brackets
The output of bash nested if script
the output of Bash If Else statements script