5- BASH Scripting – Conditional Statements (if-then, else, elif)
Welcome guys to our 5th tutorials in BASH scripting series (other tutorials are here). In this tutorial, we will be discussing some of the conditional statements (aka structured commands).
Firstly, what are Conditional statements ?
In a BASH scripts, commands run sequentially that means first line will be executed first, then next one & so on …… But there might arise a requirement when you need to execute a command only when a condition has been fulfilled. That’s where conditional commands come onto play.
So, in this tutorial we will be discussing some conditional commands. Let’s get going….
This is the most basic type of conditional (structured) command. Syntax for using it is
Let’s use it in an example
So, this seems simple enough, here when only date command runs then only we will get output i.e. “Command works”
Also, remember that we can use a number of commands in “then” statement.
These are some simple scripts where our output is provided when conditions are TRUE. So, what to do when our conditions are not TRUE, next conditional statement is the answer…
For If-then statement, we could only provide a condition for when a command is fulfilled but what to do when our condition is not fulfiled. For that very purpose we use , if-then-else
Let’s see an example script,
here you can write something else in place of “date” & you will see that output for the script will be “Command is not right”
Let’s check out another example
So, using if-then-else makes our script provide an output in both cases i.e. when our conditions are met & when they are not.
Multiple if statements
There might be need to check several conditions in our script. So to achieve that we can use multiple if statement to check all our conditions,
Above scripts looks for a user in system & if its exists then it will provide a positive response with its home directory’s contents. But when user doesn’t exists , it will look to see if it has a home directory available & will provide a directory.
Using ELIF statement
Although using multiple Ifs will get the job done but they might be hard to keep track in longer scripts & we might end up messing our scripts.
So, we use elif statement which will not only shorten our script but will also make our scripts look clean
Also, we can also use else statemen here to print an output in case neither a user exists nor a directory.
Also, remember we can use multiple elif statements is your scripts.
This completes our tutorials on conditional statements but these are not all of it. In our coming tutorials we will discuss some more conditional statements.
And please don’t forget to leave your queries/feedback in comments section below. ADIOS!!!