if-else-statement-bash-script

Bash If Else Statement: How to Use it in Your Scripts

The if else statement is the way to make decisions in Bash scripting. In this guide you will learn how to use if else in different ways as part of your scripts.

What is a Bash if else statement?

If else is a conditional statement used in Bash scripting to execute different parts of your script based on the result of the if condition. The code in the if block is executed when the if condition is true, otherwise the code in the else block is executed.

We will start by looking at the basic if else syntax so you have an understanding of how to create conditional statements in your scripts fast.

Then we will look at ways to deepen your knowledge about Bash conditional statements.

Let’s start!

Basic Syntax of The Bash If Else Statement

Every day we take hundreds of decisions and the same happens when you write code…

The logic of your program changes depending on conditions that are verified during the execution of the program.

Let’s say you are writing a Bash script and you want to check if a subdirectory called “demo” is present in the current directory.

If the directory exists the script prints “The directory demo already exists”…

Otherwise (else) it creates the directory and prints “The directory demo has been created”.

This logic is built using an if else statement.

Below you can see the Bash if else syntax (the same logic applies to pretty much every programming language):

if <expression>; then
  <command_list1>
else
  <command_list2>
fi

Where:

  • expression: is a set of one or more conditions
  • command_list1: is a list of commands executed if expression is true
  • command_list2: is a list of commands executed if expression is false

So, if the expression associated to the if statement is true, then the commands in the if block are executed. If the expression is false, the commands in the else block are executed.

As you can see, then is required before the list of commands executed in case the if condition is true.

An Example of If Else Statement in Bash

Therefore, if we go back to the example of the directory I have mentioned before, we will have something like:

if [ -d demo ]; then
  echo "The directory demo already exists"
else
  mkdir demo
  echo "The directory demo has been created"
fi

The expression [ -d demo ] allows to check if a directory with the name demo exists…

Before continuing with the next example I want to help you avoid a common error that most people do at least once in a lifetime with Bash…

…forgetting about the space around the square brackets ( [ ] ) part of the if condition.

To give you more context, the square brackets represent a command in Bash called test command.

Let’s see what happens if we remove the space after the opening square bracket and before the closing square bracket:

if [-d demo]; then
  echo "The directory demo already exists"
else
  mkdir demo
  echo "The directory demo has been created"
fi

When I run the script…

./ifelse.sh: line 3: [-d: command not found

…because of the missing space after the opening square brackets, Bash sees [-d as a single command and given that it’s not a valid command it raises the error “command not found”.

Makes sense?

Now, going back to the correct conditional statement, notice how we close the if else statement with fi, the if string reversed…

…this happens also with other Bash statements.

Do you know which one?

Time to test the if else statement

Create a Bash script called dir_check.sh:

#!/bin/bash

if [ -d demo ]; then
  echo "The directory demo already exists"
else
  mkdir demo
  echo "The directory demo has been created"
fi

Assign executable permissions to it:

chmod +x dir_check.sh

And execute it:

./dir_check.sh 
The directory demo has been created
ls -al
total 8
drwxr-xr-x  4 ec2-user  ec2-user  128 17 Feb 22:45 .
drwxr-xr-x  5 ec2-user  ec2-user  160 17 Feb 22:43 ..
drwxr-xr-x  2 ec2-user  ec2-user   64 17 Feb 22:45 demo
-rwxr-xr-x  1 ec2-user  ec2-user  143 17 Feb 22:44 dir_check.sh

Now let’s run the script again:

./dir_check.sh 
The directory demo already exists

As expected the second time we execute the script the logic in the else branch is executed.

To execute the script we have assigned execute permissions to it using the chmod command. Here you can learn how to use the chmod command more in depth.

Nested if else statements

It’s also possible to nest if else statements to create more complex logic.

For instance, if the directory demo exists we check if a file called demo_file exists inside the directory and if it doesn’t we create it:

#!/bin/bash

if [ -d demo ]; then
  echo "The directory demo already exists"
  if [ ! -f demo/demo_file ]; then
    touch demo/demo_file
    echo "The file demo/demo_file has been created"
  fi
else
  mkdir demo
  echo "The directory demo has been created"
fi

The exclamation mark ( ! ) represents the negation of the expression after it, so in this case we check if the file demo/demo_file doesn’t exist. And if this is true we create it.

Also, can you see a difference between the external if statement and the nested one?

The external one has an else condition

The nested one doesn’t have an else condition.

This shows that we don’t always need the else branch. It depends on the logic you need in your script.

Multiple Conditions in a Bash If Else Statement

So far we have used a logical expression for the if else statement that contains a single condition.

Let’s have a look how the expression can contain multiple conditions that are joined using Bash logical operators.

#!/bin/bash
   
NUMBER_OF_FILES=$(ls demo | wc -l)

if [[ -d demo && $NUMBER_OF_FILES -eq 0 ]]; then
  echo "The directory demo exists and it doesn't contain any files"
else
  if [[ -d demo && $NUMBER_OF_FILES -eq 1 ]]; then
    echo "The directory demo exists and it contains files"
  fi
fi

As you can see we are using the logical AND operator (&&) that checks the number of files in the demo directory after verifying if the demo directory exists.

Notice as well the double square brackets at the beginning and at the end of the logical expression that contains the two conditions ( [[ expression ]] ).

What happens if you replace the two square brackets with a single square bracket? Give it a try! 🙂

If Else with String Comparison

A common scenario is to write a conditional statement based on expressions that check the value of a string.

In this example I want to print the message “Today is Monday” if the value of the string DAY is equal to “Monday”.

It’s very easy to do:

#!/bin/bash
   
DAY="Monday" 

if [ $DAY == "Monday" ]; then
  echo "Today is Monday"
else
  echo "Today is not Monday"
fi

Let’s run the script:

chmod +x monday.sh
./monday.sh

Today is Monday 

What if we want to check if the DAY is not equal to “Monday”?

Here is how you can do it:

#!/bin/bash
   
DAY="Monday" 

if [ $DAY != "Monday" ]; then
  echo "Today is not Monday"
else
  echo "Today is Monday"
fi

In the code above I have made two changes:

  • Replaced the equal operator for strings ( == ) with the not equal operator ( != ). As we have seen before the exclamation mark is used in Bash to represent the negation of a condition.
  • Swapped the code in the if and else blocks considering that the logic of the if else statement is now the opposite compared to before.

Does it make sense?

Adding Elif to a Conditional Statement

The elif statement can be used to create more complex conditional statements that include multiple conditions.

Let’s see how…

I will take the script from the previous section and include an additional check to verify if DAY is “Tuesday”:

#!/bin/bash
  
DAY="Tuesday"

if [ $DAY == "Monday" ]; then
  echo "Today is Monday"
elif [ $DAY == "Tuesday" ]; then
  echo "Today is Tuesday"
else
  echo "Today is not Monday or Tuesday"
fi

The elif statement allows to add a new condition that gets verified in case the if condition is false and before reaching the else statement.

Here is what we get when we run the script:

(localhost)$ ./ifelse.sh
Today is Tuesday

Does it make sense?

Bash If Else in One Line

It’s common to see programmers trying to write code in one line.

It might sound a good idea but it’s not always the case considering that it can lead to code difficult to read.

Anyway, let see how we can write the if else statement we have seen before in one line:

#!/bin/bash

if [ -d demo ]; then
  echo "The directory demo already exists"
else
  mkdir demo
  echo "The directory demo has been created"
fi

You can write it in one line using the following two rules:

  • Statements in the if and else blocks must end with a semi-colon (;).
  • Use the space as delimiter between all the statements.
if [ -d demo ]; then echo "The directory demo already exists"; else mkdir demo; echo "The directory demo has been created"; fi 

Can you see why I don’t think it’s a good idea to write your code in a single line? 😀

Conclusion

In this Linux tutorial you have learned:

  • The basics of if else statements
  • How you can use if else in a Bash script
  • The importance of logical expressions as part of conditional statements
  • The power of using nested if else statements
  • Logical expressions that contain multiple conditions.
  • Writing a conditional statement with string comparison.
  • How to write a Bash if else in one line.

How are you going to use this now?

Let me know what script you are writing and if you have any questions! 🙂


Related FREE Course: Decipher Bash Scripting

Share knowledge with your friends!

5 comments

Leave a Reply

Your email address will not be published. Required fields are marked *