Linux Bash If-Else Conditionals

[rps-include post=6835]

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

If

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

if [ Clean.sh ] 
    then echo "Clean.sh exist" 
fi

If  Clean.sh exists then echo

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

if grep -q tmp Clean.sh
    then echo "File have temp string"
fi

Multiple Conditions with If – Elif

count=11 

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

Here we have to focus of elif statement which adds new condition to the if statement. If the count is 12 do this else if 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 exist use the following statement

file="Clean.sh" 

if [ -e $file ] 
    then echo "Clean.sh exists"  
fi

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 .

count=6 

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

[rps-include post=6835]

Leave a Comment