Shell Loop Constructs: Iterating Over Numbers, Strings, and Files
Shell scripts often require repetitive tasks. The for loop is a fundamental structure for iterating over sequences, lists, or file paths. This article covers three common types of for loops: numeric ranges, character strings, and patnhame expansion.
Numeric Iteration
Shell provides several ways to loop over numbers. The following examples print (i * 3 + 1) for i from 1 to 10.
C-style syntax:
#!/bin/bash
for ((i=1; i<=10; i++)); do
echo $((i * 3 + 1))
done
Note the double parentheses and semicolons. For an infinite loop: for ((;;)); do echo "infinite"; done.
Using seq command:
#!/bin/bash
for i in $(seq 1 10); do
echo $((i * 3 + 1))
done
seq options:
-f "%03g": format with leading zeros (three digits)-s " ": use space as separator instead of newline-w: equal width output (cannot combine with-f)- Syntax:
seq [first [increment]] last
Brace expansion:
#!/bin/bash
for i in {1..10}; do
echo $((i * 3 + 1))
done
Brace expansion {1..10} must not be quoted (single, double, or backticks).
Using awk:
awk 'BEGIN{for(i=1; i<=10; i++) print i}'
String Iteration
Loop over strings or command output.
Iterate over files in current directory:
#!/bin/bash
for i in *; do
echo "$i is a file!"
done
Iterate over script arguments:
#!/bin/bash
for i in "$@"; do
echo "$i is an argument!"
done
Iterate over explicit list:
#!/bin/bash
for i in item1 item2 item3; do
echo "$i is specified"
done
Iterate over a variable containing spaces:
#!/bin/bash
list="alpha beta gamma"
for i in $list; do
echo "$i is a word"
done
Pathname Expansion (Globbing)
Iterate over files matching a pattern.
All entries under /proc:
#!/bin/bash
for i in /proc/*; do
echo "$i is a path"
done
All shell scripts in current directory:
#!/bin/bash
for i in *.sh; do
echo "$i is a shell script"
done
Note: It is generally safer to quote variables ("$i") when expanding them inside the loop to handle spaces or special characters correctly.