In this topic, we will understand how to use if statements in Bash scripts to get our automated tasks completed.
Bash if statements are beneficial. They are used to perform conditional tasks in the sequential flow of execution of statements. If statements usually allow us to make decisions in our Bash scripts. They help us to decide whether or not to run a piece of codes based upon the condition that we may set.
Basic if Statements
A basic if statement commands that if a particular condition is true, then only execute a given set of actions. If it is not true, then do not execute those actions. If statement is based on the following format:
The statement between then and fi (If backwards) will be executed only if the expression (between the square brackets) is true.
Note: Observe the spaces used in the first line and a semicolon at the end of the first line; both are mandatory to use. If conditional statement ends with fi.
Following are some examples demonstrating the usage of if statement:
In this example, take a user-input of any number and check if the value is greater than 125.
If we enter the number 159, then the output will look like:
In this example, we demonstrate the usage of if statement with a simple scenario of comparing two strings:
In this example, we demonstrate how to compare numbers by using the if statement:
In this example, we will define how to use AND operator to include multiple conditions in the if expression:
In this example, we will define how to use OR operator to include multiple conditions in the if expression:
In this example, we will define how to use AND and OR to include multiple conditions in the if expression:
Options for If statement in Bash Scripting
If statement contains many options to perform a specific task. These options can be used for file operations, string operations, etc. Following are the some mostly used options:
You can apply as many 'if statements' as required inside your bash script. It is also possible to use an if statement inside another 'if statement'. It is known as Nested If Statement.
In this example, we will find "if a given number is greater than 50 and if it is an even number" by using nested if expression.
If we input an argument value as 100, then the output will look like:
In this topic, we discussed how we could use conditional branching in the sequential flow of execution of statements with bash if statement.