Syntax Overview
The for loop is a fundamental control structure used to execute a block of code multiple times. In Bash scripting, it supports two distinct syntax patterns depending on the iteration requirements.
1. List-Based Iteration
This structure iterates over a specific list of items. The loop variable takes on the value of each item in the sequence sequentially.
for variable_name in item1 item2 item3
do
# Commands to execute
done
The list of values is space-separated. The loop terminates once the variable has been assigned and processed for the last item in the list.
2. C-Style Syntax
This format mimics the traditional for loop found in the C programming language. It relies on three expressions enclosed in double parentheses.
for (( expression1; expression2; expression3 ))
do
# Commands to execute
done
- Expression 1: Initialization (e.g.,
i=0). - Expression 2: Condition (e.g.,
i<10). The loop runs while this is true. - Expression 3: Increment/Decrement (e.g.,
i++).
Practical Implementations
1. Iterating Over Static Data
List-Based Approach
The following script processes a predefined list of server names.
for server in web01 db01 cache01
do
echo "Processing node: $server"
done
Output:
Processing node: web01 Processing node: db01 Processing node: cache01
C-Style Approach
This example uses a counter to perform a fixed number of iterations.
for (( count=1; count<=3; count++ ))
do
echo "Attempt number: $count"
done
Output:
Attempt number: 1 Attempt number: 2 Attempt number: 3
2. Dynamic Iteration
Command Substitution
You can use the output of a command to generate the iteration list. The syntax uses backticks or $().
#!/bin/bash
# Iterate over files in the current directory
for filename in $(ls)
do
echo "Detected file: $filename"
done
Positional Parameters
If the in keyword and the list are omitted, the loop defaults to iterating over the script's command-line arguments ($@).
#!/bin/bash
for arg
do
echo "Received argument: $arg"
done
Executing this script with arguments alpha beta gamma would produce:
Received argument: alpha Received argument: beta Received argument: gamma