if..then statement in BASH

In this article, we would cover if..then statement in BASH. These are mainly conditional statements, which are used to handle decisions. If a certain condition is met or True then, a specific set of instruction is said to be executed. Otherwise, nothing happens.

if..then..else statements are extension to if..then statements. With if..then statements we could only check for a specific condition. We had nowhere to go if that specific condition wasn’t met. But, if..then..else includes else part as well. Here, if first condition isn’t met then the subsequent condition can be executed.

Then, there are nested statements. A nested statements basically has an if statement inside another if statement. Nested statement are part of larger scheme of things.

We will cover each of these conditional statement types in following sections with appropriate examples. We start with if..then statement first.

if..then statement in BASH

We start with an instruction set which checks whether a number is greater than 5 or not. Open a text editor, we have used nano and save the file as – first.sh

nano first.sh

Append the files with following lines of code –

read -p "Enter a number: " num1
if [ $num1 -gt 5 ] ; then
  echo "The number is greater than 5"
fi

Here, we read an input from user and store it in variable num1. We have used -gt to compare the input with 5. -gt is for greater than. If the condition satisfies, it will show the message that – The number is greater than 5. If the condition is not met, it returns with nothing.

To make the script executable –

chmod u+x first.sh

To execute the script –

./first.sh

if..then..else statement in BASH

Moving on to including else statement as well. We continue with the above example. Provide the message through else – if in case the user enters a number which is less than 5.

read -p "Enter a number: " num1
if [ $num1 -gt 5 ] ; then
    echo "The number is greater than 5"
else
    echo "The number is less than 5"
fi

This time around, if we enter a number which is less than 5. Then, it would return with the message – The number is less than 5. Rest of the code remains the same. But, what if the number is equal to 5?

Nested if statement in BASH

What if we want to check for all the conditions – less than, greater than and equal to. One way to check that could be through Nested if statement.

read -p "Enter a number: " num1
if [ $num1 -gt 5 ] ; then
echo "The number is greater than 5"
else
   if [ $num1 -lt 5 ] ; then
       echo "The number is less than 5"
   else
       echo "The number is equal to 5"
   fi
fi

Execute the above code and check for all the conditions. When the user provides an input, it returns with the appropriate message.

In conclusion, we have discussed if..then statement in BASH here.

Similar Posts