Linux Bash If-Else Conditionals Tutorial with Examples

If-Elif operators are used to designing the flow of the bash script. We can change the flow according to given conditions with If-Elif .


When writing scripts we have a lot of situations to make decisions. We solve the questions marks of the scripts with conditionals. For example the simplest one is we want to run a script if a directory or file exists.

if [ ] 
    then echo " exist" 

If exists then echo

The most used and simple conditional is if/then/else statement. The statement starts with if and lists conditions and closed with fi. Here [ … ] brackets look for the file and provide logic for if. Do not be afraid there is a lot of functions to test a lot of things. We will touch some of them.

if grep -q tmp
    then echo "File have temp string"

Multiple Conditions with If – Elif


if [ $count -eq 12 ] 
    then echo "Count is 1sh"
elif [ $count -eq 11 ] 
    then echo "Count is 11" 

Here we have to focus on elif statement which adds a new condition to the if statement. If the count is 12 do this else if the count is 11 do this. Simple isn’t it?

File Test Operators

While scripting there will be a lot of file interactions. Bash provides a lot of options for file testing. For example to check if a file exists to use the following statement


if [ -e $file ] 
    then echo " exists"  

Comparison Operators

In order to compare two or more variables or values comparison operators are used. In this example is the count is greater than 5 below example is used. The greater than operator is -gt .


if [ $count -gt 5 ] 
    then echo "count is greater then 5"                                                

LEARN MORE  How To Linux Bash For Loop In Files?

Leave a Comment