When working with Bash and shell scripting, you might need to use conditions in your script.

In programming, conditions are crucial : they are used to assert whether some conditions are true or not.

In this tutorial, we are going to focus on one of the conditional statement of the Bash language : the Bash if else statement.

We are going to see how you can use this statement to execute your scripts conditionally.

You will also learnt how you can use nested Bash if else statements to create more complex code.

Bash If Else Statement

In order to execute a Bash “if else” statement, you have to use four different keywords : if, then, else and fi :

  • if : represents the condition that you want to check;
  • then : if the previous condition is true, then execute a specific command;
  • else : if the previous condition is false, then execute another command;
  • fi : closes the “if, then, else” statement.

When using the “if else” statement, you will need to enclose conditions in single or double squared brackets.

if [[ condition ]]
then
  <execute command>
else
  <execute another command>
fi

Note that the “ELSE” statement is optional, if you omit it, nothing will be executed if the condition evaluates to false.

Note : you need to separate the condition from the squared brackets with a space, otherwise you might get a syntax error.

If Else Examples

Now that you know more about the Bash “if else” statement, let’s see how you can use it in real world examples.

In this section, we are going to build a script that prints a message if it is executed by the root user.

If the script is not executed by the root user, it is going to write another custom message.

In order to check whether the script is executed by root, we need to see if the UID of the caller is zero.

#!/bin/bash

# If the user is root, its UID is zero.

if [ $UID  -eq  0 ]
then
  echo "You are root!"
else
  echo "You are not root."
fi

If Else Examples bash-else-if

As stated earlier, the “else” statement is not mandatory.

If we omit in our script created earlier, we would still be able to execute the first “then” statement.

#!/bin/bash

# If the user is root, its UID is zero.

if [ $UID  -eq  0 ]
then
  echo "You are root!"
fi

If Else Examples bash-else-if-2

Now, what if you want to add additional “if” statements to your scripts?

Bash If Elif Statement

The “If Elif” statement is used in Bash in order to add an additional “if” statements to your scripts.

In order to execute a Bash “if elif” statement, you have to use five different keywords : if, then, elif, else and fi :

  • if : represents the condition that you want to check;
  • then : if the previous condition is true, then execute a specific command;
  • elif : used in order to add an additional condition to your statement;
  • else: if the previous conditions are false, execute another command;
  • fi : closes the “if, elif, then” statement.
if [[ condition ]]
then
  <execute command>
elif [[ condition ]]
then
  <execute another command>
else
  <execute default command>
fi

Again, the “ELSE” statement is optional, so you may want to omit it if you do not need a default statement.

if [[ condition ]]
then
  <execute command>
elif [[ condition ]]
then
  <execute another command>
fi

If Elif Examples

In our previous section, we used the “if else” statement to check whether a user is root or not.

In this section, we are going to check if the user is root or if the user has a UID of 1002.

If this is not the case, we are going to exit the script and return the prompt to the user.

if [[ $UID  -eq  0 ]]
then
  echo "You are root!"
elif [[ $UID  -eq 1002 ]]
then
  echo "You are user, welcome!"
else
  echo "You are not welcome here."
  exit 1;
fi

If Elif Examples elif

Congratulations, now you know how to use the “if elif” statement!

Now what if you want to have multiple conditions under the same “if” statement?

Multiple Conditions in If Else

In order to have multiple conditions written in the same “if else” statement, you need to separate your conditions with an “AND” operator or a “OR” operator.

# AND operator used in if else.

if [[ <condition_1> && <condition_2> ]];
then
   <execute command>
fi

# OR operator used in if else.
if [[ <condition_1> || <condition_2> ]];
then
   <execute_command>
else
   <execute_another_command>
fi

For example, if you want to write a script that checks that you are the root user and that you provided the correct parameter, you would write :

#!/bin/bash
 
# If the user is root and the first parameter provided is 0.
if [[ $UID -eq 0 && $1 -eq 0 ]];
then
    echo "You provided the correct parameters"
else
    echo "Wrong parameters, try again"
fi

Multiple Conditions in If Else and-operator-1

Nested If Else Statements

In some cases, you want to implement nested conditions in order to have conditions checked under preliminary conditions.

In order to have nested “if else” statements, you simply have to include the “if” statement in another “if” statement and close your nested statement before the enclosing one.

if [[ condition ]]
then  
  if [[ other condition ]]
  then
    <execute command>
  else
    <execute another command>
  fi
fi
Note : make sure to have a closing “fi” statement for every “if” statement that you open. One single “fi” is simply not enough for multiple “if” statements.

Nested Statements Examples

As an example, let’s say that you want to verify that the user is root before verifying that the first argument provided is zero.

To solve that, you would write a nested “if, then, else” statement in the following way :

#!/bin/bash

if [[ $UID -eq 0 ]]
then  
  if [[ $1 -eq 0 ]]
  then
    echo "You are allowed to execute this script."
  else
    echo "You should have provided 0 as the first argument."
  fi
fi

Nested Statements Examples nested-statements

Bash Tests

As you probably noticed, in the previous sections, we used the “-eq” operator in order to compare a variable value to a number.

We did a simple equality check, but what if you want to have an inequality check?

What if you wanted to check whether a value is greater than a given number for example?

In order to perform this, you will need Bash tests.

Bash tests are a set of operators that you can use in your conditional statements in order to compare values together.

Bash tests can be listed by running the “help test” command.

$ help test

Bash Tests help-test

When writing Bash tests, you essentially have three options :

  • Write conditions on file and directories : if they exist, if they are a character file, a device file and so on;
  • Write conditions on numbers : if they are equal to each other, if one is greater than the other;
  • Write conditions on strings : if a string variable is set or if two strings are equal to each other.

Bash File Conditions

Bash file conditions are used in order to check if a file exists or not, if it can be read, modified or executed.

Bash file tests are described in the table below :

Operator Description
-e Checks if the file exists or not
-d Checks if the file is a directory
-b Checks if the file is a block device
-c Checks if the file is a character device
f1 -nt f2 If file f1 is newer than file f2
f1 -ot f2 If file f1 is older than file f2
-r File can be read (read permission)
-w File can be modified (write permission)
-x File can be executed (execute permission)

For example, to check if a file is a directory, you would write the following script

#!/bin/bash

# Checking the first argument provided
if [[ -d $1 ]]
then  
  echo "This is a directory"
else
  echo "Not a directory"
fi

Bash File Conditions directory

Bash Number Conditions

Bash number conditions are used in order to compare two numbers : if they are equal, if one is greater than another or lower than another.

Here is a table of the most used Bash number conditions :

Operator Description
num1 -eq num2 Check if numbers are equal
num1 -ne num2 Check if numbers are not equal
num1 -lt num2 Checking if num1 is lower than num2
num1 -le num2 Lower or equal than num2
num1 -gt num2 Greater than num2
num1 -ge num2 Greater or equal than num2

For example, to check if a number is not equal to zero, you would write :

#!/bin/bash

# Checking the first argument provided
if [[ $1 -eq 0 ]]
then  
  echo "You provided zero as the first argument."
else
  echo "You should provide zero."
fi

Bash String Conditions

Bash string conditions are used to check if two strings are equal or if a string if empty.

Here is a table of the main Bash string conditions :

Operator Description
str1 = str2 Checks if strings are equal or not
str1 != str2 Checks if strings are different
-z str1 Checks if str1 is empty
-n str1 Checks if str1 is not empty

For example, to check if a user provided a value to your script, you would write :

#!/bin/bash

# Checking the first argument provided
if [[ -n $1 ]]
then  
  echo "You provided a value"
else
  echo "You should provide something"
fi

Conclusion

In today’s tutorial, you learnt about the Bash “If Else” statement.

You saw, with examples, that you can build more complex statements : using elif and nested statements.

Finally, you have discovered about Bash tests, what they are and how they are used in order to check conditions in scripts.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to check it out!

Leave a Reply

Your email address will not be published.