Bash Scripting Tutorial Part 2: Mastering if, elif, and else Statements

Welcome back to Tempcoder Tech’s Bash Scripting Tutorial series. In this episode, we will dive deep into conditional statements in Bash scripting. If you missed Part 1, you might want to check it out to get up to speed. Today, we’ll be mastering the use of if, elif, and else statements to make your scripts smarter and more powerful.

Understanding Conditional Statements

Conditional statements in programming are like decision-making tools. They allow your scripts to respond to different situations. Whether you’re automating tasks, managing system resources, or processing data, mastering these concepts is crucial.

Basic Structure of an if Statement

Let’s start with the basic structure of an if statement in Bash:

Bash
if [ condition ]; then
    # Code to execute if the condition is true
fi

In this structure, you define a condition inside square brackets. If the condition is true, the code within the then block is executed.

Example: Using if Statements

Here’s a practical example. Imagine we want to check someone’s age:

Bash
age=18
if [ $age -eq 18 ]; then
    echo 'You are 18 years old.'
else
    echo 'You are not 18 years old.'
fi

In this example, we set the age to 18 and use an if statement to check if it’s equal to 18. If true, it prints “You are 18 years old”; otherwise, it prints “You are not 18 years old.”

Handling Multiple Conditions with elif

But what if you have multiple conditions to check? This is where the elif statement comes into play. The elif statement allows you to handle multiple conditions and make your scripts more versatile.

Example: Using elif Statements

Let’s say we want to determine a grade based on a score:

Bash
score=85
if [ $score -ge 90 ]; then
    echo 'You got an A.'
elif [ $score -ge 80 ]; then
    echo 'You got a B.'
else
    echo 'You got a C or lower.'
fi

In this example, we use elif to check different conditions. If the first condition isn’t met, it proceeds to the next condition until it finds a match.

Fallbacks with the else Statement

Now, what if none of the conditions are met? That’s where the else statement shines. It provides a fallback plan for your scripts.

Example: Using the else Statement

Consider a simple example where we check if a number is less than 5:

Bash
num=7
if [ $num -lt 5 ]; then
    echo 'The number is less than 5.'
else
    echo 'The number is not less than 5.'
fi

In this case, if the condition isn’t met, the else block gets executed.

Real-World Application

To make these concepts more practical, let’s explore a real-world scenario. Imagine you’re a system administrator responsible for monitoring server disk space. The following script helps you check disk space and take appropriate actions based on the available space:

Bash
# Get available disk space in megabytes
disk_space=$(df -m / | awk 'NR==2 {print $4}')

# Define threshold values for disk space
critical_threshold=100
warning_threshold=500

# Check available disk space and take actions
if [ $disk_space -lt $critical_threshold ]; then
    echo "Critical: Disk space is running low ($disk_space MB left)."
    # Perform actions to free up space or alert administrators (e.g., remove old logs).
elif [ $disk_space -lt $warning_threshold ]; then
    echo "Warning: Disk space is getting low ($disk_space MB left)."
    # Take proactive actions to avoid reaching a critical state (e.g., notify system admins).
else
    echo "Disk space is sufficient ($disk_space MB left)."
    # No immediate action needed.
fi

In this script, we first calculate the available disk space in megabytes, set critical and warning threshold values, and then use if, elif, and else statements to take actions based on the available disk space. If the space is critically low, it alerts administrators and performs actions to free up space. If it’s in a warning state, it takes proactive measures to avoid reaching a critical state. Otherwise, it simply reports that the disk space is sufficient.

Conclusion

In this episode of our Bash Scripting Tutorial series, we’ve covered the basics of if, elif, and else statements in Bash scripting. These concepts are fundamental to making your scripts dynamic and responsive to different situations.

Practice these concepts to become a scripting and automation pro. If you found this tutorial helpful, be sure to check out our YouTube video for a visual guide. Don’t forget to like, subscribe, and share the video for more tech tutorials.