for Loop Over a List
In this page:
Basic for...in Loop
The classic for var in list; do ... done form iterates over a space-separated list of words, assigning each one to var in turn for the body to use. The list can be written directly as literal words.
Example: Basic for...in Loop
#!/bin/bash
for color in red green blue; do
echo "Color: $color"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over a Variable's Words
A variable holding several space-separated words can be looped over directly by leaving it unquoted in the in list, since Bash word-splits it into separate items. This is convenient, but only safe when you know the values don't contain meaningful embedded spaces.
Example: Looping Over a Variable's Words
#!/bin/bash
names="ada grace linus"
for n in $names; do
echo "Hello, $n"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over a Numeric Range with Brace Expansion
{start..end} brace expansion generates a sequence of numbers (or letters) without needing an external command like seq. It is evaluated by Bash itself before the loop even starts, producing a plain list of literal words.
Example: Looping Over a Numeric Range with Brace Expansion
#!/bin/bash
for i in {1..5}; do
echo "Iteration $i"
done
Login to try C/C++/Java/PHP code in the editor
Looping Over Command Substitution Output
The list after in can also come from a command substitution, letting you iterate over dynamically generated data such as filenames or lines of output. Because word splitting still applies, this works best when the values are guaranteed not to contain embedded spaces.
Example: Looping Over Command Substitution Output
#!/bin/bash
for word in $(echo "one two three"); do
echo "Got word: $word"
done
Login to try C/C++/Java/PHP code in the editor
- Forgetting to quote list items that might contain spaces when building the list from a variable, causing the loop to split on whitespace and iterate over more items than intended.
- Assuming
for x in listneeds commas between items; Bash for-loops separate list items with whitespace, not commas. - Using
for i in $(seq 1 $n)out of habit for simple numeric ranges when Bash's own brace expansion ({1..n}) or C-style for loop is simpler and avoids spawning an extra process.
- Syntax:
for var in item1 item2 item3; do ... done--vartakes each value in turn. - The list can come from literal words, a variable expansion, command substitution, or brace expansion like
{1..5}. - Quoting matters:
for f in $unquoted_listword-splits, whilefor f in "${array[@]}"preserves each array element intact. - The loop body runs once per item, in the order the items appear in the list.
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: