Bash if elif else Statement
In Bash scripting, the if, elif (else if), and else statements are used for conditional branching. They allow you to execute different blocks of code based on whether a certain condition is true or false.
Here's the basic structure:
Let's break down each part:
- if [ condition ]; then: This is the starting point of the conditional statement. The condition is placed inside square brackets ([ and ]). The then keyword indicates the beginning of the code block that will be executed if the condition is true.
- elif [ another_condition ]; then: This stands for "else if." If the initial if condition is false, the script checks this condition. If it's true, the code block following this line is executed.
- else: This is the default block of code that gets executed if none of the preceding conditions is true.
- fi: This marks the end of the conditional statement. It is "if" spelled backward.
While not strictly required by Bash, using indentation to visually group the code blocks associated with each if, elif, and else is highly recommended. It makes the script more readable and understandable for both yourself and others.
Examples:Check if a file exists
This Bash script verifies the existence of a file named "myfile.txt." It uses the conditional statement -f to check if the file exists. If it does, it outputs "File exists"; otherwise, it prints "File does not exist."
Check if a number is even or odd
In this Bash script, it checks whether the variable "num" (set to 10) is even or odd. The script uses the modulo operator to determine divisibility by 2. If the result is zero, it prints "$num is even"; otherwise, it prints "$num is odd."
Get a character from the user and display its case
This Bash script prompts the user to enter a character, then determines its case. It uses regular expressions to check if the input is lowercase or uppercase. It prints whether the character is lowercase, uppercase, or not a letter accordingly.
Conclusion
The if, elif, and else statements are used for conditional execution. They allow the script to perform different actions based on whether a particular condition or a series of conditions are true or false. The structure involves checking conditions using if, providing alternative conditions with elif, and specifying a default action with else.