Home Bash scripting Bash Scripting – Conditional Statements

Bash Scripting – Conditional Statements

Bash Conditional Expression Examples

By Karthick
Published: Updated: 12.4K views

In this guide, we will learn the usage of conditional statements in Bash scripting with examples. Decision-making is an important step in programming. There may be a situation where certain conditions have to be met and based upon that you have to write some logic. This is what a conditional statement does. The conditional statements allows you to write logic and take decisions. The concept that you read here will be the same for all the programming languages out there but with syntactic and implementation difference.

Conditional statement syntax

The building block of conditional statement in bash is as follows.

if [[ conditions ]]
then
   code
elif [[ conditions ]]
then
   code
else
   code
fi

Code explanation:

  1. The keywords "if" and "fi" mark the start and end of the conditional statement. Every if statement should be followed by the "then" keyword.
  2. Either [[ ]] or [ ] should be used to evaluate the condition. If the condition is evaluated to "True", then a block of code will be executed.
  3. A conditional statement can have one if condition and multiple elif conditions. If a condition is evaluated to be true all subsequent conditional statements are skipped.
  4. If all the if or elif block is evaluated to be false then the block of code from the "else" clause will run.
  5. Though there are no strict indentation rules, leave 2 spaces for the code block which will give better readability.

To evaluate the conditions bash has a built-in command called "test". Square brackets are the same as the test command so you can use either test command or square brackets.

$ type -a test
test is a shell builtin
test is /usr/bin/test
test is /bin/test

There are a bunch of operators supported by the test command to evaluate the conditions and we will see how to use these operators in the upcoming section. To get the list of operators you can run either one of the below commands.

$ man test
$ help test

File test operators

File test operators can be used to work with file or directory objects. Using file test operators you can validate if a given file or directory is present or not, given object is a file or directory, what type of file you are dealing with, size of the file, etc. Run the following command and look out for the file operator section.

$ man test
File test operator
File test operator

Not all the operators are used frequently but I will walk you through the most important ones.

To check if a given file is present or not use the -e flag. Here I am checking if the .bashrc file is present in my home directory or not.

if [[ -e /home/${USER}/.bashrc ]]
then
  echo "File is present"
else
  echo "File is not present"
fi
Check if file exists or not
Check if file exists or not

To check if a given directory is present or not use the -d flag. Here I am checking for the desktop directory in my home folder.

if [[ -d ~/Desktop/ ]]
then
  echo "Directory is present"
else
  echo "Directory is not present"
fi
Check if directory exists or not
Check if directory exists or not

To check if the file is non-zero-sized file, use the -s flag. Here, I have created a file named "zero_byte.txt" and appended some text.

$ touch ~/Desktop/zero_byte.txt
$ echo "Writing something" >> ~/Desktop/zero_byte.txt
$ if [[ -s ~/Desktop/zero_byte.txt ]]
then
  echo "File is not zero byte"
else
  echo "File is zero byte"
fi
Check if the file is zero bytes or not
Check if the file is zero bytes or not

You can use ! symbol with any flags which will inverse the result. I am using the same example as above but with "!" symbol. It will inverse and print the file as zero byte file, even though it is not.

$ if [[ ! -s ~/Desktop/zero_byte.txt ]]
then
  echo "File is not zero byte"
else
  echo "File is zero byte"
fi
Inverse operations
Inverse operations

Integer comparison operators

Below are the integer comparison operators which will evaluate against two given integers.

-eq => Integer X is equal to Integer Y
-ne => Integer X is not equal to Integer Y
-gt => Integer X is greater than Integer Y
-ge => Integer X is greater than or equal to Integer Y
-lt => Integer X is lesser than Integer Y
-le => Integer X is lesser than or equal to Integer Y

Every bash command returns an exit code between 0-255 and we will use the Integer comparison operators to evaluate the exit codes. In the below example, I am assigning the exit code of the nvim command to a variable called EXCODE and doing the integer comparison. Since neovim is not available, it will throw the exit code 127 (command not found error).

$ EXCODE=$(nvim;echo $?)
$ if [[ $EXCODE -eq 0 ]]
then      
  echo "nvim is available to use"
elif [[ $EXCODE -eq 127 ]]
then
  echo "Command not found, check if nvim is installed or not"
else     
   echo "Return code is other than 0 & 127. Check and fix the error"
fi
Integer comparison example
Integer comparison example

In the above example, I have used the elif statement for the first statement in this article. First the "if" condition is evaluated to check if the return code is zero, which returns false, then control is passed to elif statement and the condition is evaluated to true and runs the block of code. You can add as much elif statement to evaluate different conditions.

You can also evaluate multiple conditions in a single if or elif statement using logical AND, OR operator.

LOGICAL AND ⇒ && symbol => All the conditions should be evaluated to be true.
LOGICAL OR ⇒ || symbol => Anyone condition should be evaluated to be true.

Below is an example for a logical AND operator where the integer stored in variables X and Y are evaluated to be true.

$ X=10
$ Y=15
$ if [[ $X -eq 10 && $Y -eq 15 ]]
then
  echo "ok to proceed"
else
  echo "Not ok to proceed"
fi
Usage of Logical AND operator
Usage of Logical AND operator

Below is the example for a logical OR operator where variable X is evaluated to be true and variable Y is evaluated to be false.

$ X=10
$ Y=15
$ if [[ $X -eq 10 || $Y -eq 10 ]]
then
  echo "ok to proceed"
else
  echo "Not ok to proceed"
fi
Usage of Logical OR operator
Usage of Logical OR operator

Compact conditional statements

If you have to just write an if and else statement then you can use the shorthand way. In the shorthand way, there is no need to use if..then..else..fi keywords. You can use logical AND (&&) and logical OR (||) operators.

[[ condition ]] && << run if condition is evaluated to true >> || << run if condition is evaluated to false >>

Take a look at the below example. I am trying to check if package neofetch is available and if not available trying to install it.

$ which neofetch && echo "Neofetch already installed" || sudo apt install neofetch -y
Compact logical expression example
Compact logical expression example

Code explanation:

  • It will run the "which neofetch" command and if the return code is zero then whatever comes after && operator will run.
  • If the return code is above zero (evaluated to false), whatever comes after || operator will run.
  • This is similar to the if and else statement. The "If" statement will run only if the condition is evaluated to be true. In this case, it is AND operator. Similarly, the else clause will run only when "if" condition is evaluated to false. In this case, it is OR operator.
  • In my machine neofetch is already installed, so the exit code will be zero. It will run the echo command. If the neofetch is not installed, it will run the apt install command.

Below is another example where I am using the file test operator to check if a file is zero bytes or not.

$ [[ -s ~/.bashrc ]] && echo "Not a empty file" || echo "Empty file"
Compact logical expression test operator
Compact logical expression test operator

String comparison operators

Like Integer and File test operators, we have a set of operators to work with strings. Below are the important set of string operators.

-z => Check if string is NULL.
-n => Check if string is not NULL.
== => Check for string equality.
!= => Check for string inequality.

To check if the string is NULL or not NULL, use the -z and -n flag. I am using the compact conditional statement syntax to evaluate the condition.

$ [[ -z "Howdy" ]] && echo "String is NULL" || echo "String is not NULL"
$ [[ -n "Howdy" ]] && echo "String is not NULL" || echo "String is NULL"
String null or not
String null or not

To check if two strings are equal, use == operator. Strings are case sensitive, so you have to run the comparison keeping this point in mind.

$ X="Linux"
$ Y="Linux"
$ [[ $X == $Y ]] && echo "Equal" || echo "Not equal"
String equality
String equality

To check if two strings are not equal, use != operator.

$ [[ $X != $Y ]] && echo "Not Equal" || echo "Equal"
Not equal to operator

Conclusion

In this article, we have seen how to work with conditional statements in Bash. We have also seen how to use file test, integer, and string operators. Finally, we discussed how to write compact conditional statements using logical AND and logical OR operators with examples.

For any feedback or suggestion, please use the comment section and we will be happy to revert back.

You May Also Like

1 comment

Jalal Hajigholamali October 24, 2021 - 1:58 pm

Hi,
Thanks a lot
Very nice article

Reply

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

This website uses cookies to improve your experience. By using this site, we will assume that you're OK with it. Accept Read More