Bash Script – Using “elif” (Else If) for multiple condition

Bash scripting is a powerful tool for automating tasks and making your computer do things the way you want it to. Often, in our scripts, we need to make decisions based on different conditions. For example, you might want your script to do one thing if it’s sunny outside, another if it’s raining, and yet another if it’s snowing.

In the world of Bash scripting, we use “if” statements to make these decisions. However, sometimes one “if” statement isn’t enough. What if you have multiple conditions to check? That’s where “elif” comes into play.

In this blog post, we’re going to explore the world of “elif” statements. We’ll start by understanding why they are important and then dive into how to use them effectively. Whether you’re a beginner or already familiar with Bash scripting, this guide will help you master the art of handling multiple conditions in your scripts. So, let’s get started!

Introducing “elif” Statements

In the world of Bash scripting, making decisions is a common task. You might want your script to behave differently depending on various conditions. For example, imagine you’re writing a script that categorizes files. You want it to sort files into different folders based on their size and type. This is where “elif” (short for “else if”) statements become incredibly handy.

Why Do We Need to Handle Multiple Conditions in Scripts?

Imagine you have a script that needs to check if a number is positive, negative, or zero. You could start with a simple “if” statement like this:

#!/bin/bash

number=5

if [ $number -gt 0 ]; then
  echo "It's a positive number."
else
  echo "It's not a positive number."
fi

This script works well for checking if the number is positive or not. But what if you also want to check if it’s zero or negative? Using only “if” and “else” might not be enough. You could write additional “if” statements, but it can quickly become messy and less readable.

The Structure and Purpose of “elif” Statements

Here’s where “elif” comes to the rescue. It allows you to handle multiple conditions in a much cleaner and organized way. Let’s rewrite the previous script using “elif”:

#!/bin/bash

number=5

if [ $number -gt 0 ]; then
  echo "It's a positive number."
elif [ $number -eq 0 ]; then
  echo "It's zero."
else
  echo "It's a negative number."
fi

Now, with “elif,” you can efficiently check for three conditions in a structured manner: positive, zero, and negative. The script evaluates each condition one by one and executes the block of code associated with the first true condition it encounters.

Comparing “elif” to “if” and “else” Statements

“If” statements: They are used to check a single condition and execute code accordingly.

“Else” statements: They provide an alternative code block to execute when the “if” condition is false.

“Elif” statements: They are used when you have multiple conditions to check, and each condition has its own code block. “Elif” allows you to cascade through these conditions in an organized way until one of them is true.

Real-World Scenario: Categorizing Files

Let’s consider a practical example. You have a folder full of files, and you want to categorize them into different subfolders based on their size and type. Here’s a simplified script using “elif” statements to achieve this:

#!/bin/bash

file="example.txt"
size=$(stat -c %s "$file")
extension="${file##*.}"

if [ $size -gt 1000 ]; then
  echo "The file is large."
elif [ $size -gt 100 ]; then
  echo "The file is medium-sized."
else
  echo "The file is small."
fi

if [ "$extension" == "txt" ]; then
  echo "The file is a text file."
elif [ "$extension" == "jpg" ]; then
  echo "The file is an image."
else
  echo "The file is of an unknown type."
fi

In this script, “elif” statements allow us to categorize files both by size and type effectively. It’s a clear and organized way to handle multiple conditions in your Bash scripts.

Multiple Conditions with “elif”

In Bash scripting, “elif” (short for “else if”) is your go-to tool when you need to evaluate multiple conditions sequentially and efficiently. Let’s dive into how “elif” works, its syntax, and practical examples to illustrate its usefulness.

How to Use “elif” to Evaluate Multiple Conditions Sequentially

Using “elif” is like having a list of conditions to check one after the other until one of them is true. The syntax is straightforward:

if condition1; then
  # Code to execute if condition1 is true
elif condition2; then
  # Code to execute if condition2 is true
elif condition3; then
  # Code to execute if condition3 is true
else
  # Code to execute if none of the conditions are true
fi

Important Note: “elif” statements are evaluated in order from top to bottom, and the first true condition encountered will execute its associated code block. If none of the conditions is true, the code block under “else” (if provided) will run.

Showcasing Practical Examples with Different “elif” Scenarios

Example 1: Sorting Numbers into Categories (e.g., positive, negative, zero)

#!/bin/bash

number=5

if [ $number -gt 0 ]; then
  echo "It's a positive number."
elif [ $number -eq 0 ]; then
  echo "It's zero."
else
  echo "It's a negative number."
fi

In this example, the script evaluates whether a number is positive, zero, or negative and then executes the corresponding code block.

Example 2: Categorizing Files Based on Extensions

#!/bin/bash

file="example.txt"
extension="${file##*.}"

if [ "$extension" == "txt" ]; then
  echo "The file is a text file."
elif [ "$extension" == "jpg" ]; then
  echo "The file is an image."
else
  echo "The file is of an unknown type."
fi

This script checks the file extension and categorizes it as a text file, an image, or an unknown type based on the “elif” conditions.

Example 3: Grading System with Multiple Ranges (A, B, C, etc.)

#!/bin/bash

score=85

if [ $score -ge 90 ]; then
  echo "Grade: A"
elif [ $score -ge 80 ]; then
  echo "Grade: B"
elif [ $score -ge 70 ]; then
  echo "Grade: C"
elif [ $score -ge 60 ]; then
  echo "Grade: D"
else
  echo "Grade: F"
fi

In this example, the script assigns grades based on the score within specific score ranges using “elif” statements.

Nesting “elif” Statements

Nesting “elif” (else if) statements within other “if” or “else” blocks is a powerful technique in Bash scripting. It allows you to create more complex conditionals by combining multiple levels of decision-making. Let’s explore the concept of nested “elif” statements, their structure, and a practical use case to illustrate their usefulness.

Concept of Nesting “elif” Statements

Nesting “elif” statements involves placing one set of “elif” conditions inside another set of “if” or “else” blocks. This structure allows you to evaluate conditions in a hierarchical manner. If the conditions in the outer “if” or “elif” are true, their associated code blocks are executed. If not, the inner “elif” statements are checked, and so on.

Indentation and Structure

Proper indentation is crucial when nesting “elif” statements to maintain code clarity and readability. Here’s the basic structure:

if outer_condition1; then
  # Code for outer_condition1
  if inner_condition1; then
    # Code for inner_condition1
  elif inner_condition2; then
    # Code for inner_condition2
  else
    # Code for inner_else
  fi
elif outer_condition2; then
  # Code for outer_condition2
else
  # Code for outer_else
fi

Each level of nesting increases the indentation, making it easy to see which “elif” corresponds to which “if” or “else” block.

Practical Use Case: Handling Both File Type and Size Within Categories

Consider a scenario where you have a collection of files, and you want to categorize them into folders based on both their file types (e.g., text, image) and their sizes (e.g., small, medium, large). Here’s a simplified script using nested “elif” statements to accomplish this:

#!/bin/bash

file="example.txt"
size=$(stat -c %s "$file")
extension="${file##*.}"

if [ "$extension" == "txt" ]; then
  echo "The file is a text file."
  if [ $size -gt 1000 ]; then
    echo "The file is large."
  elif [ $size -gt 100 ]; then
    echo "The file is medium-sized."
  else
    echo "The file is small."
  fi
elif [ "$extension" == "jpg" ]; then
  echo "The file is an image."
  if [ $size -gt 1000 ]; then
    echo "The image is high-resolution."
  elif [ $size -gt 100 ]; then
    echo "The image is medium-resolution."
  else
    echo "The image is low-resolution."
  fi
else
  echo "The file is of an unknown type."
fi

In this script, we first check the file’s extension and categorize it. Then, within each file type category, we evaluate its size and further categorize it. This demonstrates the power of nested “elif” statements in handling complex decision-making scenarios in a structured and organized way.

Best Practices for Using “elif”

When working with “elif” (else if) statements in your Bash scripts, following best practices can help you maintain clean and readable code. Let’s explore some of these practices and how they contribute to well-structured scripts.

Use Meaningful Condition Names and Comments

When defining conditions in your “elif” statements, use clear and descriptive variable names and comments to explain the purpose of each condition. This makes your code more understandable, especially for others who may read or collaborate on your scripts.

#!/bin/bash

# Good practice: Use clear condition names and comments
if [ "$file_extension" == "txt" ]; then
  # This file is a text file.
elif [ "$file_extension" == "jpg" ]; then
  # This file is an image.
else
  # The file is of an unknown type.
fi

Keep the Order of Conditions Logical and Organized

Arrange your “elif” conditions in a logical order, starting with the most specific or common conditions and progressing towards the more general or catch-all conditions. This organization ensures that the script evaluates conditions efficiently and makes it easier to follow.

#!/bin/bash

# Logical order: Specific to general
if [ "$file_extension" == "jpg" ]; then
  # This file is an image.
elif [ "$file_extension" == "txt" ]; then
  # This file is a text file.
else
  # The file is of an unknown type.
fi

Limit Excessive Nesting for Clarity:

While nesting “elif” statements can be useful, avoid excessive nesting, as it can make your code harder to understand. If you find yourself nesting too deeply, consider refactoring your script to use functions or alternative control structures like “case” statements.

#!/bin/bash

# Excessive nesting
if [ "$file_type" == "image" ]; then
  if [ "$file_extension" == "jpg" ]; then
    # Handle JPG image.
  elif [ "$file_extension" == "png" ]; then
    # Handle PNG image.
  else
    # Handle other image types.
  fi
elif [ "$file_type" == "text" ]; then
  if [ "$file_extension" == "txt" ]; then
    # Handle TXT file.
  else
    # Handle other text file types.
  fi
else
  # Handle unknown file types.
fi

Consider Using a Case Statement for Complex Scenarios

For more complex scenarios with multiple conditions, consider using a “case” statement (also known as “switch” in some programming languages). “Case” statements can provide a cleaner and more structured way to handle multiple conditions, especially when dealing with a large number of possibilities.

#!/bin/bash

case "$file_extension" in
  txt)
    # This file is a text file.
    ;;
  jpg)
    # This file is an image.
    ;;
  *)
    # The file is of an unknown type.
    ;;
esac

In this example, the “case” statement makes it easier to handle various file extensions without excessive “elif” statements.

By following these best practices, you can create Bash scripts that are not only functional but also more maintainable and accessible to both yourself and others who may work with your code.

Conclusion

In the world of Bash scripting, mastering the use of “elif” (else if) statements is a valuable skill. These statements empower you to make complex decisions in your scripts, providing a structured and organized approach to handling multiple conditions.

We’ve explored the fundamental concepts of “elif” statements, from their introduction to their practical application. They allow you to evaluate conditions sequentially, executing code blocks associated with the first true condition encountered.

To use “elif” effectively, remember these best practices: use meaningful condition names and comments, maintain a logical order of conditions, avoid excessive nesting for clarity, and consider “case” statements for complex scenarios.

By implementing these practices, you’ll create clean, readable, and maintainable Bash scripts that efficiently handle various conditions and make your automation tasks more manageable. So, go ahead and apply what you’ve learned about “elif” statements to enhance your scripting capabilities. Happy scripting!

Frequently Asked Questions (FAQs)

What is an “elif” statement in Bash scripting?

An “elif” statement, short for “else if,” is a part of Bash scripts used to handle multiple conditions. It allows you to check one condition after another in a structured way and execute specific code blocks when conditions are met.

When should I use “elif” statements in my Bash scripts?

How do I structure “elif” statements in my script?

Are “elif” statements evaluated in order?

Can I nest “elif” statements within other “if” or “else” blocks?

What are some best practices for using “elif” statements?

When should I consider using a “case” statement instead of “elif” statements?

Where can I practice using “elif” statements in Bash scripting?

Are “elif” statements specific to Bash scripting, or can I use them in other programming languages?

Where can I find more resources to learn about Bash scripting and “elif” statements?

Related Articles