Unix / Linux - Shell Decision Making

Hello, aspiring programmers! Today, we're going to dive into the exciting world of decision making in Unix and Linux shell scripting. As your friendly neighborhood computer teacher, I'm here to guide you through this journey, step by step. So, grab your favorite beverage, get comfortable, and let's embark on this adventure together!

Unix / Linux - Decision Making

The if...else statements

Imagine you're at a crossroads in your code, and you need to make a decision based on certain conditions. That's where the if...else statements come in handy. They're like the traffic lights of programming, guiding your code down different paths based on whether conditions are true or false.

Basic if statement

Let's start with the simplest form of the if statement:

if [ condition ]
then
    command1
    command2
    ...
    commandN
fi

Here's a real-world example:

#!/bin/bash
age=18

if [ $age -ge 18 ]
then
    echo "You are old enough to vote!"
fi

In this example, we're checking if the age variable is greater than or equal to 18. If it is, the message "You are old enough to vote!" will be displayed.

if...else statement

Now, what if we want to do something when the condition is false? That's where the else clause comes in:

if [ condition ]
then
    command1
    command2
    ...
    commandN
else
    alternative_command1
    alternative_command2
    ...
    alternative_commandN
fi

Let's modify our voting example:

#!/bin/bash
age=16

if [ $age -ge 18 ]
then
    echo "You are old enough to vote!"
else
    echo "Sorry, you're too young to vote."
fi

Now, if the age is less than 18, it will display the message "Sorry, you're too young to vote."

if...elif...else statement

Sometimes, life (and code) isn't just black and white. We often need to check multiple conditions. That's where the elif (else if) clause comes in:

if [ condition1 ]
then
    command1
elif [ condition2 ]
then
    command2
else
    alternative_command
fi

Let's create a more complex example:

#!/bin/bash
grade=75

if [ $grade -ge 90 ]
then
    echo "A - Excellent!"
elif [ $grade -ge 80 ]
then
    echo "B - Good job!"
elif [ $grade -ge 70 ]
then
    echo "C - You passed."
else
    echo "F - You need to study more."
fi

This script evaluates a student's grade and provides appropriate feedback based on different grade ranges.

The case...esac Statement

Now, imagine you're at a buffet with multiple food options. That's what the case...esac statement is like in programming. It allows you to match a value against a list of patterns and execute commands based on the match.

The basic syntax looks like this:

case expression in
    pattern1)
        command1
        command2
        ...
        commandN
        ;;
    pattern2)
        command1
        command2
        ...
        commandN
        ;;
    *)
        default_command
        ;;
esac

Let's look at a practical example:

#!/bin/bash
fruit="apple"

case $fruit in
    "apple")
        echo "It's a delicious red fruit!"
        ;;
    "banana")
        echo "It's a yellow curved fruit!"
        ;;
    "orange")
        echo "It's a juicy citrus fruit!"
        ;;
    *)
        echo "I don't know that fruit."
        ;;
esac

In this example, we're matching the value of fruit against different patterns. If it matches "apple", it will echo the corresponding message. If it doesn't match any of the specified patterns, it will execute the default case (*).

Multiple patterns

You can also match multiple patterns for the same set of commands:

#!/bin/bash
day=$(date +%A)

case $day in
    Monday|Tuesday|Wednesday|Thursday|Friday)
        echo "It's a weekday. Time to work!"
        ;;
    Saturday|Sunday)
        echo "It's the weekend. Time to relax!"
        ;;
    *)
        echo "What planet are you on?"
        ;;
esac

This script checks the current day of the week and outputs whether it's a weekday or weekend.

Comparison of if...else and case...esac

Now, let's compare these two decision-making structures:

Feature if...else case...esac
Complexity Can handle complex conditions Best for simple value matching
Readability Can become hard to read with many conditions More readable with multiple conditions
Performance Slightly slower for many conditions Faster for many conditions
Flexibility Can use any type of condition Limited to pattern matching

In my years of teaching, I've found that students often struggle with choosing between if...else and case...esac. Here's a simple rule of thumb: if you're checking a single variable against multiple possible values, case...esac is your friend. For everything else, stick with if...else.

Remember, programming is like cooking. These decision-making structures are your ingredients, and with practice, you'll learn when to use each one to create the perfect dish... I mean, script!

In conclusion, decision making is a crucial aspect of shell scripting. It allows your scripts to adapt and respond to different situations, making them more powerful and flexible. Whether you're using if...else or case...esac, you're now equipped with the tools to make your scripts smarter. Keep practicing, and soon you'll be writing scripts that can make decisions faster than you can say "sudo"!

Credits: Image by storyset