This post will cover how to use nested if-else statements with bash scripting. Conditions are usually checked from inside the scripts, but it is frequently desirable to check for a condition outside the script and act accordingly. For example, you may need to check for some environmental variable that influences how your script does its job. In such cases, you should use a nested if statement.
Nested if statements are often used with the test command in order to execute one of two different tasks based on whether or not an optional condition is met. It is also possible to make decisions based on multiple conditions using more than two branches.
There are a few different ways to create the if statement in bash. The first is to use the keyword if. The second is using an elif statement. In both cases, the condition will be checked inside the script and any actions that are assigned to a particular branch inside that if statement will be taken when it is true.
The following example creates a simple if-else statement:
#!/bin/bash #This script checks for a specific directory present on the system if [[ ! -d “$1” ]]; then echo “Directory $1 not found. Terminating.” exit 1 fi else echo “Directory $1 exists.” fi
Here is an example of how you would use an elif statement in a script:
#!/bin/bash #This script checks for the existence of two directories if [[ ! -d “$1” ]]; then echo “Directory $1 not found. Terminating.” exit 1 fi elif [[ ! -d “$2” ]]; then echo “Directory $2 not found. Terminating. ” fi else if [[ ! -d “$3” ]]; then echo “Directory $3 not found. Terminating.” exit 1 fi fi
The if might be used to check for a specific condition:
#!/bin/bash #This script checks for a specific file present on the system if [[ ! -f “$1” ]]; then echo “File $1 not found. Terminating.” exit 1 fi else echo “File $1 exists. ” fi
The elif is used to check for a specific condition:
#!/bin/bash #Create a Log Report Template if [[ ! -f “$1” ]]; then echo “Please create LogReportTemplate.txt in the directory $1. ” fi elif [[ ! -f “$2” ]]; then echo “Please create LogReportTemplate2.txt in the directory $2. ” fi else if [[ ! -f “$3” ]]; then echo “Please create LogReportTemplate3.txt in the directory $3. ” fi
The elif can be used to check for multiple conditions, but in order to not affect the script’s overall flow, it should only be used when you want something to happen if some of the conditions are met. In the case of an if-else statement, the test command will work similarly.
Conclusion
Nested if-else statements are often used with the test command in order to execute one of two different tasks based on whether or not an optional condition is met. It is also possible to make decisions based on multiple conditions using more than two branches. In order to not affect the script’s overall flow, it should only be used when you want something to happen if some of the conditions are met.
Leave a Reply