← Back to Bash Course | Chapter 4: Loops | Lesson 2 of 14

for Loop Over a List

A for loop lets your script repeat a block of commands once for each item in a list, automatically handing you the current item on every pass.

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

bash
#!/bin/bash
for color in red green blue; do
    echo "Color: $color"
done

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

bash
#!/bin/bash
names="ada grace linus"
for n in $names; do
    echo "Hello, $n"
done

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

bash
#!/bin/bash
for i in {1..5}; do
    echo "Iteration $i"
done

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

bash
#!/bin/bash
for word in $(echo "one two three"); do
    echo "Got word: $word"
done
Common Mistakes
  1. 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.
  2. Assuming for x in list needs commas between items; Bash for-loops separate list items with whitespace, not commas.
  3. 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.
Chapter Summary
  • Syntax: for var in item1 item2 item3; do ... done -- var takes 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_list word-splits, while for f in "${array[@]}" preserves each array element intact.
  • The loop body runs once per item, in the order the items appear in the list.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.