A for loop in Bash is a control structure that allows you to repeat a set of commands for each item in a list, over a range, or based on other criteria. It’s commonly used for tasks like iterating over files in a directory, processing elements in an array, or executing a block of code multiple times.

Basic Syntax

The basic syntax of a for loop in Bash is as follows:

1
2
3
4
for VARIABLE in LIST
do
# Commands to be executed
done
  • VARIABLE is a placeholder that takes the value of each item in LIST one by one.
  • LIST can be a list of values, a range of numbers, or even a command that generates a list.
  • The do and done keywords define the start and end of the loop block.

    Example 1: Loop Over a List of Values

    Here’s an example of a for loop that iterates over a list of words:
    1
    2
    3
    4
    for word in apple banana cherry
    do
    echo "The fruit is: $word"
    done

Output:

1
2
3
The fruit is: apple
The fruit is: banana
The fruit is: cherry

Example 2: Loop Over a Range of Numbers

You can also loop over a sequence of numbers:

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

Output:

1
2
3
4
5
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example 3: Loop Over Files in a Directory

A common use case is looping over files in a directory:

1
2
3
4
for file in /path/to/directory/*
do
echo "Processing $file"
done

This loop will iterate over each file in the specified directory and execute the commands inside the loop for each file.
For example, read all files from /home/john directory.

1
2
3
4
for file in /home/john/*
do
echo "Processing $file"
done

Output:

1
2
3
4
5
6
7
8
9
10
Processing /home/john/Desktop
Processing /home/john/Documents
Processing /home/john/Downloads
Processing /home/john/Music
Processing /home/john/Pictures
Processing /home/john/Public
Processing /home/john/Templates
Processing /home/john/Videos
Processing /home/john/snap
Processing /home/john/tut

Example 4: C-Style For Loop

Bash also supports a C-style for loop, similar to loops in languages like C or Java:

1
2
3
4
for (( i=1; i<=5; i++ ))
do
echo "Iteration $i"
done

Output:

1
2
3
4
5
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5

Summary

  • for loops are versatile and can be used to iterate over lists, ranges, or output from commands.
  • They are useful for automating repetitive tasks, processing files, and more.

This should give you a solid understanding of how to use for loops in Bash scripts.