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.
Table of Contents
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:
- The keywords
"if"
and"fi"
mark the start and end of the conditional statement. Every if statement should be followed by the"then"
keyword. - Either
[[ ]]
or[ ]
should be used to evaluate the condition. If the condition is evaluated to "True", then a block of code will be executed. - 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. - If all the
if
orelif
block is evaluated to be false then the block of code from the"else"
clause will run. - 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
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
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
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
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
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
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
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
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
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
andelse
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 theapt 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"
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"
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"
To check if two strings are not equal, use !=
operator.
$ [[ $X != $Y ]] && echo "Not Equal" || echo "Equal"
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.
Bash scripting guides:
- Bash Scripting – String Manipulation
- Bash Scripting – Printf Command Explained With Examples
- Bash Scripting – Indexed Array Explained With Examples
- Bash Scripting – Associative Array Explained With Examples
- Bash Scripting – For Loop Explained With Examples
- Bash Scripting – While And Until Loop Explained With Examples
- Bash Redirection Explained With Examples
- Bash Scripting – Variables Explained With Examples
- Bash Scripting – Functions Explained With Examples
- Bash Echo Command Explained With Examples In Linux
- Bash Heredoc Tutorial For Beginners
1 comment
Hi,
Thanks a lot
Very nice article