For Loop in Bash
The for
loop in Bash is used to iterate through a list of items, files, numbers, or any set of values. It executes a set of commands for each item in the list, making it an essential tool for automation and scripting.
Basic Syntax
variable
: A placeholder for each item in the list.list
: A space-separated list of items.do
anddone
: Enclose the block of commands.
Examples of For Loops
1. Loop Through a List of Words
Script:
Output:
2. Loop Through Numbers
Script:
Output:
{1..5}
: Generates numbers from 1 to 5.
3. Loop Through a Range with Step
Script:
Output:
{1..10..2}
: Generates numbers from 1 to 10, incrementing by 2.
4. Loop Through Files in a Directory
Script:
Output:
/path/to/directory/*
: Matches all files in the directory.
5. Loop Using Command Substitution
Script:
Output:
$(command)
: Executes a command and uses its output as the list.
6. C-Style For Loop
Bash also supports a C-like syntax for for
loops.
Script:
Output:
((i=1; i<=5; i++))
: Initializes, checks, and increments the loop variable.
7. Nested For Loop
You can nest for
loops to iterate over multiple lists.
Script:
Output:
Best Practices
Quote Variables: Use double quotes around variables to handle spaces in values.
Avoid Hardcoding Paths: Use variables for paths or filenames to make scripts reusable.
Debugging Loops: Add
set -x
at the top of your script to trace execution.
Common Use Cases
Batch Renaming Files
Performing Tasks on Multiple Servers
Processing Log Files
Conclusion
The for
loop in Bash is a versatile tool for iterating over lists, processing files, and automating repetitive tasks. It’s a fundamental concept that every Bash user should master.
Let me know if you'd like examples of advanced use cases or troubleshooting tips!