Control Flow and Decision Making

Section 2: Control Flow and Decision Making

Lesson 1: Conditional Statements

Conditional statements in shell scripts allow for decision-making based on specified conditions.

1.1 Using if, else if, and else Statements

#!/bin/bash

# Using if, else if, and else statements


read -p "Enter a number: " num


if [ "$num" -gt 0 ]; then

    echo "The number is positive."

elif [ "$num" -lt 0 ]; then

    echo "The number is negative."

else

    echo "The number is zero."

fi

1.2 Comparisons and Logical Operators

#!/bin/bash

# Comparisons and logical operators


read -p "Enter your age: " age


if [ "$age" -ge 18 ] && [ "$age" -le 65 ]; then

    echo "You are of working age."

else

    echo "You are either too young or too old to work."

fi


Lesson 2: Case Statements

Case statements provide a concise way to implement switch-like functionality.

#!/bin/bash

# Case statements


read -p "Enter a fruit: " fruit


case "$fruit" in

    "apple")

        echo "You selected an apple." ;;

    "banana")

        echo "You selected a banana." ;;

    "orange")

        echo "You selected an orange." ;;

    *)

        echo "Unknown fruit." ;;

esac


Lesson 3: Looping in Shell Scripts

Looping allows for repeated execution of commands in shell scripts.

3.1 For Loops

#!/bin/bash

# For loops

for i in {1..5}; do

    echo "Iteration $i"

done

3.2 While Loops 

#!/bin/bash

# While loops


count=1


while [ "$count" -le 5 ]; do

    echo "Count: $count"

    ((count++))

done

3.3 Until Loops 

#!/bin/bash

# Until loops


counter=1


until [ "$counter" -gt 5 ]; do

    echo "Counter: $counter"

    ((counter++))

done

3.4 Loop Control Statements (break, continue) 

#!/bin/bash

# Loop control statements


for i in {1..10}; do

    if [ "$i" -eq 5 ]; then

        break  # Exit the loop when i is 5

    fi


    if [ "$i" -eq 3 ]; then

        continue  # Skip the rest of the loop for i=3

    fi


    echo "Iteration $i"

done

Understanding control flow and decision-making constructs in shell scripting enables the creation of dynamic and responsive scripts. In the next sections, we'll explore more advanced scripting techniques and practical applications.