Learn Decision Making using if conditions in Linux Shell Scripting

0
5852

In the last article “Test Conditions”, we have learned how to create test statements that check for many various conditions. We have learned how to test numbers for equality, inequality, greater than, less than, etc. We have also tested strings for zero-length, non-zero length and equality/inequality. We have seen how to check if certain file exists and whether it is of a specific type or not. At last, we have seen how to combine two or more conditions using the Logical operators to create a composite condition.
Now, it is time to build upon what we have learned. Did you think the only use of test conditions is to execute them, and check their exit status?!! Of course not!!
The test conditions are just base for Decision Making and Repeated Execution (using while and until loops). In this article, we are going to learn Decision Making using if conditions.

if Statement
Our everyday’s life is full of decisions. Every moment you take decisions, intentionally and unintentionally. The weather forecast said that the temperature today is expected to be 40 °C, so you decided to go to work in casual wear instead of the formal suit. In your work, the canteen guy was absent, so you decided to order a delivery. On your way home, the bus was late for more than 15 minutes, so you decided to take a taxi. When you get back home, you felt very tired, so you decided to sleep an hour and have dinner after you wake up.

Have you seen how many decisions taken in the above simple situations?! This is life!!  And our computer programs (that try to simulate and solve real life problems) should support this decision making issue. For this purpose, the superstar of this article was created: the if statement.

Syntax:

```if TESTCONDITION; then
command1
command2
…
command
fi
```

Where the TESTCONDITION is any simple or composite test condition (like the ones we learned in the previous article).

Example
Consider a script that prompts the user to enter two numbers, divides them, and prints the result to the user. The script should make sure the divisor is not zero. (We know from mathematics that division by zero is not allowed)

Let’s execute it and see:

Now, to the explanation:

• The read statement asks the user to enter two numbers, and assigns them to the variables x and y.
• An if statement checks whether y is not equal to 0. If so, the statements between then and the closing delimiter fi will be executed. If not, nothing executed.

So simple and logic.

if..else..fi
In the previous example, if the user enters a divisor equal to 0, the if condition evaluates to false, so, nothing is executed and the program exits silently. I think you agree with me that it would be better to notify the user that he has entered a wrong input. In such situations, else jumps into the scene.

Syntax:

```if  TESTCONDITION; then
command1
command2
…
commandn
else
command_1
command_2
..
command_n
fi
```

Now, if the user enters 0 for the divisor, the else part will be executed. Let’s write this modified version.

Example
Here is the modified version of the divide script.

Now, let’s see if this would make a difference:

When the user entered zero value for the divisor, the script printed an error message notifying the user that the divisor shouldn’t be 0. Then, it exits with an exit value 1 to indicate unsuccessful execution.

Now, let’s explain things:

• The if statement checks whether y is not equal to 0. If so, the statements between then and the else will be executed.
• If not, the else part is executed; so, statements between the else and the fi will be executed.
• A friendly error message is printed to the user informing him that the divisor should never be 0
• The program exits with an exit value 1, indicating a non-zero exit status. If another script executes this script, it could check its exit status to see whether it is executed successfully or with errors.

if..elif..else..fi
syntax:

```if  TESTCONDITION1; then
command1
command2
…
commandn
elif TESTCONDITION2; then
command_1
command_2
..
command_n
else
command__1
command__2
..
command__n
fi
```

Example
In this example, we are going to write a script that asks the user to enter a number. The script will check the number and tell whether it is an odd number, even number, or 0.

Let’s execute it:

It works as expected.

* * * * * *

One-Line Test Conditions
There will be cases wherein we need to execute only one statement if the condition is met, or if the condition is not met. For such cases, instead of using the if..else structure, there is a shorter method that saves lines and typing.

Syntax:

```TESTCONDITION && command_to_be_executed

TESTCONDITION || command_to_be_executed
```

Examples

• The following line checks whether the file foo.txt exists. If so, it will be deleted.
```[[email protected] ~]# [ -f foo.txt ] && rm -i foo.txt
rm: remove 'foo.txt'? y
```
• The following line checks whether the directory /tmp/new exists. If not, it will be created.
```[email protected] ~]# [ -d /tmp/newdir ] || mkdir /tmp/newdir
[[email protected] ~]# ls /tmp/
dir1     dir2     dir3     busybox.man     newdir
```

* * * * * *

In this article, we have tackled an important topic: the decision making using IF conditions. We have learned how the if..elif..else..fi structure works. We have also illustrated the concept with several examples to make the idea clear. At last, we talked about the one-line conditions. We have seen how they could be a shorter alternative to if conditions in case we need to execute only one statement if (or if not) the condition is met.

I hope you find this article useful. See you in the next article “Loops”.