The for loop in Bash is a control structure that allows you to iterate over a list of items, executing a block of code for each item. It’s a powerful tool for automating repetitive tasks in scripts. Let’s break down how it works.
Basic Syntax
The basic syntax of a for loop in Bash is as follows:
for variable in list; do
# Commands to execute
done
variable: This is a placeholder that takes the value of each item in the list during each iteration.list: This can be a sequence of items, a range, or a variable containing multiple values.do ... done: This block contains the commands that will be executed for each item in the list.
Example of a Simple for Loop
Here’s a simple example that prints numbers from 1 to 5:
for i in 1 2 3 4 5; do
echo "Number: $i"
done
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Looping Through a List of Arguments
You can also use a for loop to iterate through command-line arguments using the $@ variable. Here’s an example:
#!/bin/bash
for arg in "$@"; do
echo "Argument: $arg"
done
If you run this script with arguments like Hello World, it will output:
Argument: Hello
Argument: World
Key Points
- Iteration: The loop iterates over each item in the list, executing the commands inside the
do ... doneblock for each item. - Variable Scope: The variable defined in the
forloop (e.g.,iorarg) is local to the loop and can be used within the loop body. - Quoting: Using quotes around
"$@"ensures that arguments with spaces are treated as single items.
Conclusion
The for loop is a fundamental construct in Bash scripting that allows for efficient iteration over lists, making it easier to automate tasks. If you want to practice more with loops, consider exploring additional examples and exercises in Bash scripting labs.
Feel free to ask if you have more questions or need further clarification!
