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:

if [ condition ]; then # Code to be executed if the condition is true elif [ another_condition ]; then # Code to be executed if the first condition is false and this condition is true else # Code to be executed if none of the above conditions are true fi

Let's break down each part:

  1. 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.
  2. 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.
  3. else: This is the default block of code that gets executed if none of the preceding conditions is true.
  4. fi: This marks the end of the conditional statement. It is "if" spelled backward.
Indentation:

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

if [ -f "myfile.txt" ]; then echo "File exists" else echo "File does not exist" fi

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

num=10 if [ $((num % 2)) -eq 0 ]; then echo "$num is even" else echo "$num is odd" fi

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

read -p "Enter a character: " char if [[ $char =~ ^ [a-z]$ ]]; then echo "$char is lowercase" elif [[ $char =~ ^ [A-Z]$ ]]; then echo "$char is uppercase" else echo "$char is not a letter" fi

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.