Loops
for over a list, while with arithmetic, and why {1..$n} does not do what it looks like.
- Loop over words, files and number ranges
- Count with while and (( ))
- Know when brace expansion happens and why it cannot use variables
The two loop scripts both print the numbers 1 upwards:
for i in {1..5}
do
echo $i
done
i=1
while [[ $i -le 10 ]] ; do
echo "$i"
((i += 1))
done
A for loop in Bash walks over a list of words. {1..5} is brace expansion: before the loop runs, Bash rewrites it into 1 2 3 4 5. The same loop walks over files with a glob — for f in *.sh — or over a command’s output.
The while loop repeats as long as its test command succeeds. ((i += 1)) is arithmetic evaluation, C-style, with no $ needed inside.
The brace-expansion trap
Brace expansion happens before variables are expanded, so it never sees their values:
n=3
for i in {1..$n}; do echo "[$i]"; done # prints [{1..3}] once
Bash expanded $n too late, and the loop ran once over the literal string. For a range that depends on a variable, use the arithmetic for, which counts correctly, or seq:
for ((i = 1; i <= n; i++)); do echo "$i"; done # 1 2 3
for i in $(seq 1 "$n"); do echo "$i"; done # 1 2 3
Reading lines
To loop over the lines of a file — the repository’s file.txt, say — do not use for line in $(cat file.txt), which splits on every space. The robust form is:
while IFS= read -r line; do
echo "got: $line"
done < file.txt
The < file.txt redirection feeds the file to the loop’s standard input, and IFS= read -r keeps leading spaces and backslashes intact.
Try it yourself. Write a loop that prints the number of lines in every .sh file in the folder using wc -l, and make it work for a file named my script.sh. Then count down from 10 to 1 with brace expansion, with the arithmetic for, and with seq.