Shell Script · For Loop

Shell Scripting · Lesson 10

For Loop

Master for loop in bash scripting. Iterate over files and values. Real examples like log cleanup. Most used loop in automation.

What is a For Loop?

A for loop allows you to repeat a block of code multiple times by iterating over a list, range, or sequence.

It is commonly used when the number of iterations is known in advance.

Why Use a For Loop?

Repetition

Repeat commands multiple times without rewriting code.

List Processing

Process files, numbers, or words easily.

Automation

Automate repetitive system tasks efficiently.

For Loop Syntax

for loop syntax
syntax
for variable in list
do
commands
done

For Loop Examples

1. Basic For Loop

Loop through a list of values and execute a command for each value.

terminal — bash
for-loop
for i in 1 2 3 4 5
do
echo "Number: $i"
done

2. Using Range with Brace Expansion

Generate a numeric sequence using brace expansion.

terminal — bash
for-loop
for i in {1..5}
do
echo "Count: $i"
done

3. Loop Through Command Output

Iterate over output of another command.

terminal — bash
for-loop
for file in $(ls)
do
echo "File: $file"
done

4. C-Style For Loop

C-style loop syntax similar to programming languages.

terminal — bash
for-loop
for (( i=1; i<=5; i++ ))
do
echo "Value: $i"
done

Best Practices

Tips for Writing Clean Loops

  • Avoid complex logic inside loops.
  • Use meaningful variable names.
  • Prefer C-style loops for numeric ranges.
  • Test loops with small data first.

Practice Task – For Loop

  • Print numbers from 1 to 10.
  • List all files in a directory.
  • Print even numbers between 1 and 20.

Next lesson: While Loop