Bash IF statement is used to execute a set of instructions or commands based on whether a certain condition is satisfied or not. This post should serve you as a cheat sheet to most of the scenarios that you might encounter in your everyday scripting tasks that uses conditional execution.

Simple ‘IF’ statement Example

Let’s assign a value of ‘1’ to variable ‘x’ and use ‘IF’ statement to check the value of x.

x=1
if [ x == 1 ]
then
echo "value of x is 1"
elif [ x == 2 ]
then
echo "value of x is 2"
else
echo "value of x is something else"
fi

value of x is 1

‘x == 1’ is the condition. Below are a few common examples of using different conditions for evaluation.

# if string is empty, then..
if [ -z $str ]	

# if string is Not empty, then..
if [ -n $str ]	

# if two numbers are equal, then..
if [ $num1 -eq $num2 ]	

# if two numbers are not equal, then..
if [ $num1 -ne $num2 ]	

# if num1 is lesser than num2, then..
if [ $num1 -lt $num2 ]	

# if num1 is lesser than OR equal to num2, then..
if [ $num1 -le $num2 ]	

# if num1 is greater than num2, then..
if [ $num1 -gt $num2 ]	

# if num1 is greater than OR equal to num2, then..
if [ $num1 -ge $num2 ]	

# If str1 matches the regex then..
# The regex used in the below example checks if $str is a valid email address.
if [[ $str =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$ ]]	
# note the double square brackets is used here for reqular or conditional expressions.

# if $num1 is lesser than $num2, then..
if (( $num1 < $num2 ))	        
# note that double round brackets is used for arithmatic operation.

# noclobber option prevents overwriting existing files with the > operator. 
if [ -o noclobber ]	If OPTIONNAME is enabled, then.. 

# If the condition (name is vijay) is not true
if [ ! name == "vijay" ]	

# If both conditions are true, then..
if [ name == "vijay" ] && [ age -gt 18 ]	

# if one of the conditions is true, then..
if [ name == "vijay" ] || [ age -gt 18 ]	

File conditions

# if file Exists..
[ -e file.txt ]	

# if file is readable
[ -r file.txt ]	

# if the file is a Symlink
[ -h file.txt ]	

# if the file name specified is a Directory
[ -d files ]	

# if file is Writable
[ -w file.txt ]	

# if file Size is > 0 bytes
[ -s file.txt ]	

# if the file name specifued is actually a file and not a directory
[ -f file.txt ]	

# if file is Executable
[ -x file.txt ]	

if file1.txt is newer than file2.txt
[ file1.txt -nt file2.txt ]	

if file1.txt is older than file2.txt
[ file1.txt -ot file2.txt ]	

if file1.txt and file2.txt are the same
[ file1.txt -ef file2.txt ]	

Nesting IF statements

IF statements in bash supports nesting. (i.e one if statement inside another)

a=4
if [ "$a" -gt 0 ]
then
if [ "$a" -lt 6 ]
then
echo "The value of a is in range 0-6"
fi
fi

The value of a is in range 0-6

However, a better way to check the above condition is by using Conditional Logic.

if [ "$a" -gt 0 ] && [ "$a" -lt 6 ]
then
echo "The value of a is in range 0-6"
fi

The value of a is in range 0-6