Labs ICT
โญ Pro Login

Shell Loops

Loops let you repeat things without copying and pasting. Need to rename a hundred files? Process every line in a log? Run the same command on ten servers? Loops are the answer. The shell has two main kinds: for and while.

The for loop

for loops over a list of items. The syntax is for var in list; do ...; done. The list can be words, filenames from a wildcard, or the output of a command.

#!/bin/bash
for fruit in apple banana cherry
do
    echo "I like $fruit"
done

Output:

I like apple
I like banana
I like cherry
Try it Yourself โ†’

Looping over files

The most common use of for is looping over files. Use a wildcard in the list and the shell expands it to matching filenames.

#!/bin/bash
for file in *.txt
do
    echo "Processing $file..."
    wc -l "$file"
done
Try it Yourself โ†’

The while loop

while loops keep going as long as a condition is true. They are great for reading files line by line, watching for changes, or repeating until a task finishes.

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

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Try it Yourself โ†’

Break and continue

break exits the loop immediately. continue skips the rest of the current iteration and moves to the next one. These give you fine control over loop execution.

#!/bin/bash
for num in 1 2 3 4 5 6 7 8 9 10
do
    if [ $num -eq 3 ]
    then
        echo "Skipping 3"
        continue
    fi
    if [ $num -eq 8 ]
    then
        echo "Reached 8, stopping"
        break
    fi
    echo "Number: $num"
done

Output:

Number: 1
Number: 2
Skipping 3
Number: 4
Number: 5
Number: 6
Number: 7
Reached 8, stopping
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which shell construct repeats a block of code for each item in a list?