Linux - Loops & Conditions in Bash

Loops & Conditions in Bash

In Bash scripting, loops and conditions allow your script to make decisions and perform repetitive tasks automatically. They are the backbone of automation, helping you execute commands efficiently without manual input. Understanding how they work is essential for writing powerful and flexible shell scripts.


1. Conditional Statements (If, Else, Elif)

Conditional statements help your script take different actions based on certain conditions—such as checking if a file exists or if a number is greater than another.

a) if statement

Used to run a block of code only if a condition is true.

if [ $age -gt 18 ]; then
    echo "You are an adult"
fi

b) if–else statement

Runs one block when condition is true and another when false.

if [ $marks -ge 50 ]; then
    echo "Pass"
else
    echo "Fail"
fi

c) if–elif–else statement

Allows multiple conditions.

if [ $score -ge 90 ]; then
    echo "Grade A"
elif [ $score -ge 75 ]; then
    echo "Grade B"
else
    echo "Grade C"
fi

2. Loops in Bash

Loops allow you to repeat a set of commands multiple times, saving time and reducing mistakes.


a) For Loop

Used when you know how many times you want to repeat something.

Example:

for i in 1 2 3 4 5
do
    echo "Number: $i"
done

Looping through files:

for file in *.txt
do
    echo "Processing $file"
done

b) While Loop

Runs as long as the condition remains true.

Example:

count=1
while [ $count -le 5 ]
do
    echo "Count: $count"
    count=$((count+1))
done

c) Until Loop

Opposite of the while loop. It runs until a condition becomes true.

x=1
until [ $x -gt 5 ]
do
    echo "Value: $x"
    x=$((x+1))
done

d) Infinite Loop

Useful for services and continuous monitoring.

while true
do
    echo "Running..."
    sleep 2
done

3. Case Statement (Switch-Like Condition)

Used when you want to match a variable against multiple values. It is cleaner than writing many if-else statements.

echo "Enter a fruit:"
read fruit

case $fruit in
    apple) echo "Apples are red or green." ;;
    banana) echo "Bananas are yellow." ;;
    orange) echo "Oranges are citrus." ;;
    *) echo "Unknown fruit!" ;;
esac

Why Loops & Conditions Matter in Bash?

  • Automate tasks efficiently

  • Handle dynamic inputs

  • Reduce manual effort

  • Enable complex logic in scripts

  • Improve accuracy and consistency


 

Mastering loops and conditions in Bash makes your shell scripts smarter, more powerful, and capable of solving real-world automation problems with ease.