Bash/Shell

Bash if else Statement With Examples

By ayed_amira , on 04/24/2020 , updated on 09/10/2020 , 1 comment - 7 minutes to read
bash if else statement intro

Overwiew

In this new tutorial we will learn how to use Bash conditions and how to use them in your different shell scripts. Conditions are one of the fundamental concepts in programming. It also allows you to execute or not execute a piece of code depending on the conditions you define. This makes it possible to create scripts that are more complex and can solve more important tasks.

Without further delay let’s start this tutorial!

Bash If Statement

This is the simplest form of the if statement. Its principle is very simple. If the expression in the condition is respected then the condition IF gives as value True and so the code block is executed ( As shown in the diagram below)

bash-if-statement

Its syntax is as follows:

if EXPRESSIONS
then
  STATEMENTS
fi

The if statement always starts with the keyword “if”. This keyword is followed by the expression you want to test. The instruction block is always between the keyword “then” and “fi” which indicates the end of the statement block in the if statement.

Let’s take as an example this following shell script which allows to check if a person is major or not :

#!/bin/bash

echo -n "Enter an age: "
read AGE

if [[ $AGE -gt 17 ]]
then
  echo "You are of legal age"
fi

You can save this code in a testif.sh file to test by yourself from the command line:

bash testif.sh
Result: 
Enter an age: 18
You are of legal age

The shell script will ask you to enter your age. If your age is over 17 (18 and over) the condition will be respected and the code will execute the echo command which tells you that you are over 18. What happens if you enter an age lower than 18? It will not happen at all since the condition is not respected. To deal with this kind of situation there is the ELSE statement that allows to solve this.

Note : It is recommended that you always indent your code and separate the code blocks with blank lines. This allows your code to be more readable and organized. You can either use an indentation of 2 or 4 spaces.

Bash If..Else Statement

The syntax of the if..else statement is :

if EXPRESSION
then
  STATEMENTS1
else
  STATEMENTS2
fi

STATEMENT1 will be executed only if the expression is true. If not, STATEMENT2 will be executed instead.

Note : There can only be one ELSE clause in an IF statement.

Let’s go back to the previous script that determines if you are over 18 or not:

#!/bin/bash

echo -n "Enter an age: "
read AGE

if [[ $AGE -gt 17 ]]
then
  echo "You are of legal age"
else 
  echo "you are a minor"
fi

This time if you enter an age under 18, the program will return the message “you are a minor”.

Bash if..elif..else Statement

The syntax of the if..elif..else statement is :

if EXPRESSION1
then
  STATEMENTS1
elif EXPRESSION2
then
  STATEMENTS2
else
  STATEMENTS3
fi

STATEMENT1 will be executed if EXPRESSION1 is true. If it is not the case STATEMENT2 will be executed if EXPRESSION2 is true. STATEMENT3 will be executed if neither expression is true.

Note : The conditions are executed sequentially. That is, the program will first check the first condition and then the second if the first condition is wrong and so on.

Here’s an example that explains this:

#!/bin/bash

echo -n "Enter an age: "
read AGE

if [[ $AGE -gt 17 ]]
then
  echo "You are of legal age"
elif [[ $AGE -gt 10 ]]
then
  echo "you're a teenager"
else
  echo "you are a child"
fi

Bash Nested if Statements

It is possible to nest several if statements in bash. This makes it possible to test several conditions. Here is a syntax showing a use case for nested IF statements :

if EXPRESSION1
then
  if EXPRESION2
  then
    STATEMENT1
  else
    STATEMENT2
  fi
else
  if EXPRESSION3
  then
    STATEMENT2
  else
    STATEMENT4
  fi
fi

Here’s an example:

value=$( grep -ic "amiradata" /etc/passwd )
if [ $value -ge 1 ]
then

  if [ $value -eq 1 ]
  then
    echo "Amiradata : 1"
  elif [ $value -eq 2 ]
  then
    echo "Amiradata : 2"
  fi
else
  echo "I dont found amiradata :("
fi

Note : It is preferable to use the CASE statement which is more readable than nested if statements.

Bash Boolean Operations

The logical operators AND and OR allows you to test several conditions in IF statements :

  • AND : &&
  • OR : ||
if [[ -n $1 ]] && [[ -r $1 ]]
then
  echo "File exists and is readable"
fi

The IF statement will check whether variable $1 is not empty AND whether variable $1 is readable or not. If both conditions are met then the program will display the ECHO message.

if [[ -z $1 ]] || [[ ! -r $1 ]]
then
  echo "Either you didn't give me a value or file is unreadable"
fi

The IF statement will check whether variable $1 is not empty OR whether variable $1 is readable or not. If both conditions are met then the program will display the ECHO message.

Bash Tests

In our previous examples we have used the operator “-gt” to see if a person is an adult or not. This is called testing. These basic tests are a set of operators that you can use in our conditions to compare values with each other.

These different tests are available using the following command:

$ help test

There are mainly 3 options :

  • Write conditions on the file and directories: whether they exist, whether it is a character file, a device file, etc.
  • Write the conditions on the numbers: if they are equal to each other, if one is less than the other.
  • Conditions for writing to strings: if a string variable is defined or if two strings are different from each other.

Bash File Conditions

These conditions are used to test if, for example, a file exists or not, if it is a directory etc..

Here is the list of tests available in bash :

OperatorDescription
-eChecks if the file exists or not
-réChecks if the file is a directory
-cChecks if the file is a character device
-bChecks if the file is a block device
f1 -nt f2If file f1 is newer than file f2
f1 -ot f2If file f1 is older than file f2
-rThe file can be read
-wThe file can be edited
-xThe file can be executed

Here is an example to check if the file exists :

#!/bin/bash

# Checking the first argument provided
if [[ -e $1 ]]
then  
  echo "This file exists"
else
  echo "This file doesn't exists"
fi

Bash Number Conditions

Basic number conditions are used to compare two numbers. Here are the different possible comparisons in bash :

OperatorDescription
number1 -eq number2Check if the numbers are equal
number1 -ne number2
Check if the numbers are not equal
number1 -lt number2
Checking if number1 is less than number2
number1 -le number2
Less than or equal to number2
number1 -gt number2
Greater than number2
number1 -ge number2
Greater than or equal to number2

For example, to verify that a number is less than or equal to 100, we will write:

#!/bin/bash

if [[ $1 -le 100 ]]
then  
  echo "the number in argument is less than or equal to 100"
else
  echo "the number in argument is greater than 100 "
fi

Bash String Conditions

Here is a table of the main conditions of the Bash chain:

OperatorDescription
string1 = string2Checks if the strings are equal or not
string1 != string2Checks if the strings are different
-z string1
Check if string1 is empty
-n string1Checks if string1 is not empty

Here is an example to check if a string is not empty :

#!/bin/bash

if [[ -n $1 ]]
then  
  echo "Not empty"
else
  echo "Empty"
fi

Summary

  • if : represents the condition you want to check
  • then : if the previous condition is true, then execute a specific statement
  • elif : used to add an additional condition to your statement
  • else : if the previous condition is false, then run another command
  • fi : closes the “if, elif, then” statement
  • && : Perform the and operation
  • || : Perform the or operation

We are coming to the end of the tutorial, I hope this one will be useful in the creation of your shell scripts. If you want to know more about the shell, I advise you to read this book (As an Amazon Partner, I make a profit on qualifying purchases) :

Back to the learning section

ayed_amira

I'm a data scientist. Passionate about new technologies and programming I created this website mainly for people who want to learn more about data science and programming :)

Comments

On 04/25/2020 at 7 h 25 min, indoor playground said:


Excellent post. I was checking constantly this blog and I am inspired!
Very useful info particularly the closing section :) I
care for such information a lot. I used to be seeking this certain info for a very lengthy time.

Thanks and good luck.


Your reply will be revised by the site if needed.

Leave a comment

Your comment will be revised by the site if needed.