if statement

One of the most commonly used programming constructs is the conditional execution, or the if statement. This statement is used to carry out certain commands based on testing a condition. For example, you might want to execute certain commands if the condition is true, and other commands if the condition is false.

The basic structure of the if statement looks like this:

if [ conditional-expression ]
then
commands
else
other-commands
fi

First, the condition inside the brackets is evaluated. If the condition is true, the commands following the then keyword are executed. Otherwise, the commands following the else keyword are executed. The fi (if backward) keyword marks the end of the if block.

A simple example that will help you understand the concept. Let’s say that we want to find out the user’s age. We can ask a user to enter his or her age, and then execute different commands, depending on the input:

#!/bin/bash
echo “How old are you?”
read age
if [ “$age” -ge 21 ] ; then
echo “You are old enough. Welcome!”
else
echo “Sorry, you are not allowed to be here, you are too young!”
fi

First, we ask a user to enter his/her age. The number that the user has entered is then assigned to the variable age. If the user is 21 years old or older (specified by -ge 21 ), the You are old enough. Welcome! message is displayed. If that is not the case, the Sorry, you are not allowed to be here, you are too young! message is displayed:

linux if else statement

Notice the spacing after [ and before ].

 

Here is a list of all comparison operators:

-eq – equal to
-ne – not equal to
-lt – less than
-le – less than or equal to
-gt – greater than
-ge – greater than or equal to

You can also use the elif statement to test for any number of conditions. For example:

#!/bin/bash
echo “How old are you?”
read age
if [ “$age” -le 21 ] ; then
echo “You are too young. Leave now!”
elif [ “$age” -ge 60 ] ; then
echo “You are too old! Go away!”
else
echo “You are just the right age. Welcome!”
fi

You can see that the script above displays the You are too young. Leave now! message if the user is 21 years old or younger, the message You are too old! Go away! if the user is 60 years old or older, and the You are just the right age. Welcome! if neither of the conditions above is true:

linux elif statement

Here is another example. Let’s say that we want to test if a file exists, and then execute different commands based upon that condition. We can use the -e option inside the brackets to test whether the file exists:

#! /bin/bash
file=test_file
if [ -e $file ]
then
echo “File $file exists.”
else
echo “File $file doesn’t exist.”
fi

linux file exists example

Here is a list of the file test operators for the bash shell:

-e – file exists
-f – file exists and is not a directory
-d – directory exists
-x – file is executable
-w – file is writable
-r – file is readable

Geek University 2022