The if and else condition is used in decision making in shell script. If the given condition is true, the command is executed otherwise won’t. Condition is the comparison between the values. For example, you have seen in some websites, “Enter only if you are 18+”. If you click on Yes you can enter into the website and if you click No you won’t be allowed to enter the website.
The expression that will be used in shell scripting are:
1. “-gt” = Greater than
2. “-lt” = Less than
3. “-eq” = Equals to
4. “-ne” = Not equals to
3. “-ge” = Greater than or Equals to
4. “-le” = Less than or Equals to
The syntax for “if” statement is:
if test condition
this command will be executed
Let’s just take a simple example of 18+ websites. The simple logic is, if you are 18 and older, you are allowed to enter otherwise not.
echo "Enter your age:: c" read age if test $age -ge 18 then echo "You are allowed to enter" fi
If the user enters the age greater than or equals to 18 he/she will be prompted will the message “You are allowed to enter” and If the user enter the number less than 18 the program will exit. See this, to run and execute this file. Let me show you the output.
Now, add the else statement to the if statement.
echo "Enter your age:: c" read age if test $age -ge 18 then echo "You are allowed to enter" else echo "You are not allowed to enter" fi
Now, if you input the number less than 18 you will be prompted will the message “You are not allowed to enter”.
Nested or Multilevel If..Else Statement:
If you have to work on more than two conditions you will use Nested if else statement. Here’s the simple script that you will make you familiar with nested if..else statement.
#!/bin/sh echo "Enter the age of your child: c" read age if test $age -le 1 then echo "Use mother's milk" elif test $age -le 5 then echo "Baby is growing up" elif test $age -le 10 then echo "Really grown up" else echo "**Age should be less than or equals to ten only**" fi
This is a simple script. See the output below.