Control Statement in Linux Shell Scripting.

Control statements in Linux shell scripting are essential for creating complex and dynamic scripts. They allow you to control the flow of execution based on conditions, loops, and other criteria. Let's go over the basic control statements in Bash scripting:

                          Before actually using the control statement, you need to understand about different operators in shell scripting. 

      Linux shell scripting offers a variety of operators for different types of comparisons and operations. Here’s a comprehensive list:

1. Arithmetic Operators

2. Relational Operators

3. Boolean Operators

4. String Operators

5. File Test Operators

1. Conditional Statements

if-else

The if-else statement executes commands based on a condition.

bash

#!/bin/bash
echo "Enter your age:"
read age

if [ "$age" -ge 18 ]; then
    echo "You are an adult."
else
    echo "You are a minor."
fi

if-elif-else

The if-elif-else statement handles multiple conditions.

bash

#!/bin/bash
echo "Enter a number:"
read number

if [ "$number" -gt 0 ]; then
    echo "The number is positive."
elif [ "$number" -lt 0 ]; then
    echo "The number is negative."
else
    echo "The number is zero."
fi

2. Case Statements

The case statement is used to match a variable against multiple patterns.

bash

#!/bin/bash
echo "Enter a letter:"
read letter

case $letter in
    [a-z])
        echo "You entered a lowercase letter."
        ;;
    [A-Z])
        echo "You entered an uppercase letter."
        ;;
    [0-9])
        echo "You entered a digit."
        ;;
    *)
        echo "You entered a special character."
        ;;
esac

3. Loops

for Loop

The for loop iterates over a list of items.

bash

#!/bin/bash
for i in 1 2 3 4 5
do
    echo "Number: $i"
done

while Loop

The while loop executes commands as long as a condition is true.

bash

#!/bin/bash
counter=1
while [ $counter -le 5 ]
do
    echo "Counter: $counter"
    counter=$((counter + 1))
done

until Loop

The until loop executes commands as long as a condition is false.

bash

#!/bin/bash
counter=1
until [ $counter -gt 5 ]
do
    echo "Counter: $counter"
    counter=$((counter + 1))
done

4. Loop Control

break

The break statement exits the loop entirely.

bash

#!/bin/bash
for i in 1 2 3 4 5
do
    if [ $i -eq 3 ]; then
        break
    fi
    echo "Number: $i"
done

continue

The continue statement skips the remaining commands in the current loop iteration and moves to the next iteration.

bash

#!/bin/bash
for i in 1 2 3 4 5
do
    if [ $i -eq 3 ]; then
        continue
    fi
    echo "Number: $i"
done

These control statements are fundamental building blocks in shell scripting and allow you to write more advanced and interactive scripts.