Introduction
Hello! In this article, we’ll learn about for loops.
for is a construct for repetitive processing (loops). Used when “processing list elements one by one” or “repeating from 1 to 10”, that kind of thing.
What is a for Loop?
for is a control structure for repeating processing a specified number of times or over a range.
Useful for batch processing multiple files or doing something with sequential numbers. You can easily automate repetitive manual work.
Basic Syntax
List-based Form
|
|
C-style Form (Numeric Loop)
|
|
Usage Examples
Example 1: Basic List Loop
|
|
Output:
|
|
Example 2: Numeric Range
|
|
Output:
|
|
{1..5} specifies range from 1 to 5.
Example 3: C-style Loop
|
|
Output:
|
|
Some people might be more familiar with this style.
Example 4: File Loop Processing
|
|
Output:
|
|
Can process all .txt files in current directory.
Example 5: Array Loop
|
|
Output:
|
|
Can process array elements one by one.
Example 6: Loop Command Output
|
|
Process file contents line by line.
Example 7: Increment by 2
|
|
Output:
|
|
{start..end..increment} specifies step size.
Tips & Notes
-
Wildcards are convenient: Can batch process with
*.txt,*.jpg, etc.1 2 3for img in *.jpg; do convert "$img" "${img%.jpg}.png" done -
Filenames with spaces: Enclose in double quotes
1 2 3 4for file in *.txt; do cat "$file" # Correct cat $file # Error if filename has spaces done -
No matching files: If no files match
*.txt,*.txtitself becomes the list1 2 3 4for file in *.txt; do [ -f "$file" ] || continue # Skip if file doesn't exist echo "$file" done -
break and continue: Break loop or skip iteration
1 2 3 4 5 6 7 8 9 10 11 12 13for i in {1..10}; do if [ $i -eq 5 ]; then break # Exit loop fi echo $i done for i in {1..5}; do if [ $i -eq 3 ]; then continue # Skip this iteration fi echo $i done -
seq command also available: For older systems where
{1..10}doesn’t work1 2 3for i in $(seq 1 10); do echo $i done
Practical Usage
Batch File Rename
|
|
Backup Script
|
|
Batch Directory Creation
|
|
Log File Processing
|
|
Ping Multiple Servers
|
|
Batch File Content Conversion
|
|
Summary
In this article, we learned about for loops.
Key Points:
- Repeat processing with
for - Can loop over lists, ranges, files, etc.
- Batch process multiple files with wildcards
- Enclose variables in double quotes for safety
Super useful for batch file processing or repeating the same work multiple times. Work that would be tedious manually can be finished with a single script.
Keep learning Linux commands!