December 5, 2026

Bash For Loop Examples That Survive Spaces in Filenames

A laptop showing a dark terminal window with lines of script text

Three files sit in a folder: notes.txt, report 2025.txt and a b c.txt. A common Bash one-liner meant to loop over them, for f in $(ls *.txt), runs six times instead of three, handing the loop the fragments a, b, c.txt, notes.txt, report and 2025.txt. Nothing about that loop is a typo. It is doing exactly what the shell was told. Every example below was run in GNU Bash 5.2.21 for this post, and the output shown is what came back, including the failures.

Video: Learn Linux TV on YouTube

The two shapes of a Bash for loop

Looping over a list of words

The GNU Bash Reference Manual gives the first form as for name [ [in words …] ; ] do commands; done. Bash expands the words, then runs the commands once for each word, with the variable set to that word.

for fruit in apple pear plum; do
  echo "$fruit"
done

Output:

apple
pear
plum

The C-style arithmetic loop

The second form will look familiar to anyone who has written C or JavaScript: for (( expr1 ; expr2 ; expr3 )). The manual says the first expression runs once, then the commands repeat while the second is non-zero, with the third evaluated after each pass.

n=3
for ((i=0; i<n; i++)); do
  printf '%s ' "$i"
done

Output: 0 1 2

What happens with nothing after the name

Leave off the in part entirely and the loop runs “once for each positional parameter that is set,” according to the manual, as if in "$@" had been written. Inside a script or function, for arg; do … done walks the arguments, and it keeps quoted arguments whole. Calling it with the arguments x and "y z" printed two lines, x and y z, not three.

Red file folders neatly arranged on a shelf

Counting with ranges

Brace expansion

The quickest way to count is a brace range. The manual’s brace expansion page describes a sequence expression of the form {x..y[..incr]}, where x and y are integers or letters.

for i in {1..5}; do printf '%s ' "$i"; done      # 1 2 3 4 5
for i in {0..20..5}; do printf '%s ' "$i"; done  # 0 5 10 15 20
for i in {01..10}; do printf '%s ' "$i"; done    # 01 02 03 ... 10

That last one is handy for numbered filenames. The manual’s rule: if either end “begins with a zero, each generated term will contain the same number of digits.”

The variable trap

This one catches almost everyone once:

n=3
for i in {1..$n}; do printf '[%s] ' "$i"; done

Output: [{1..3}]

One pass, with the literal text {1..3}. The manual states that brace expansion “is performed before any other expansions.” When Bash looks at the braces, $n is still just the characters $n, so the pattern isn’t a valid sequence and gets left alone. Then the variable expands, too late to matter.

Two fixes that work with variables

The C-style loop handles variables natively, as shown above. The other route is the seq utility from GNU coreutils:

for i in $(seq 1 "$n"); do printf '%s ' "$i"; done   # 1 2 3

seq is a separate program, so it works anywhere coreutils is installed, but it does start an extra process. For simple counting, the arithmetic loop keeps everything inside Bash.

Speed, for the curious

Timed on the same machine, an empty loop of 100,000 passes took about 0.097 seconds with {1..100000}, about 0.096 seconds with $(seq 1 100000) and about 0.141 seconds with the C-style loop. These were single runs on one sandbox, so treat them as rough. The practical lesson is that loop style rarely matters at this scale. What goes inside the loop will dominate.

Looping over files without breaking them

Why $(ls) fails

Back to the three files. Here is the broken version and its real output:

for f in $(ls *.txt); do echo "<$f>"; done
<a>
<b>
<c.txt>
<notes.txt>
<report>
<2025.txt>

ls prints names as text. The unquoted $( … ) then gets split on spaces, tabs and newlines, so a filename with a space becomes two or three words. Greg Wooledge’s long-running Bash Pitfalls page lists this exact loop as pitfall number one and is blunt about it: “there is no trick that can make it work.”

The glob does it right

Let the shell match the files itself:

for f in *.txt; do echo "<$f>"; done
<a b c.txt>
<notes.txt>
<report 2025.txt>

Three files, three passes. A glob produces each matching filename as one word, spaces and all, so nothing gets split. The remaining rule is to quote "$f" everywhere it is used inside the loop.

When nothing matches

Run the same loop in a folder with no CSV files:

for f in *.csv; do echo "<$f>"; done

Output: <*.csv>

By default, a pattern that matches nothing stays as the literal pattern, and the loop runs once with a fake filename. A script that then tries to open *.csv will fail in a confusing way. The shopt documentation describes the fix: with nullglob set, patterns that match no files “expand to nothing and are removed.”

shopt -s nullglob
for f in *.csv; do echo "<$f>"; done   # prints nothing
shopt -u nullglob

Going into subfolders

The same page covers globstar: when set, ** “will match all files and zero or more directories and subdirectories.” So shopt -s globstar followed by for f in **/*.txt walks a whole tree without reaching for find.

A conveyor belt in a large warehouse

Arrays and lines of text

Quote the array expansion

Arrays are where quoting stops being style and starts being correctness. The Bash manual’s array page says that inside double quotes, "${name[@]}" “expands each element of name to a separate word.”

arr=("first item" second "third one")
for x in "${arr[@]}"; do echo "<$x>"; done
<first item>
<second>
<third one>

Drop the quotes and the same array comes out as five words: first, item, second, third, one. Three elements in, five passes out, and the bug looks like the data’s fault.

Reading a file line by line is a while loop

A for loop over $(cat file) has the same splitting problem as $(ls). Lines are read with while:

while IFS= read -r line; do
  echo "<$line>"
done < l.txt

With a two-line file holding line one and line two, that printed exactly those two lines, spaces intact. IFS= keeps leading and trailing whitespace. For -r, the manual’s builtins page says that with it, “backslash does not act as an escape character.”

Files with truly strange names

Spaces are the common problem. Newlines are the nasty one: Linux allows a newline inside a filename, and any loop that treats output as lines will cut that file in two. The robust pattern pairs find -print0, which ends each name with a null byte, with a read that splits on nulls:

while IFS= read -r -d '' f; do
  printf '<%s>\n' "$f"
done < <(find . -name '*.log' -print0)

Tested against three files, including one named odd, newline, name.log, plus sub/deep file.log and top.log, it produced exactly three entries, with the newline still inside the first name. The < <( … ) part is process substitution: it feeds the loop from the command’s output without a pipe.

Why not just pipe into the loop

A pipe looks simpler, and for printing it works. The trouble shows up when the loop changes a variable. Bash’s pipelines page states that each command in a multi-command pipeline “is executed in its own subshell, which is a separate process.” Anything the loop sets dies with that subshell.

count=0
printf 'a\nb\n' | while read -r l; do count=$((count+1)); done
echo "after pipe: $count"        # after pipe: 0

count=0
while read -r l; do count=$((count+1)); done < <(printf 'a\nb\n')
echo "after procsub: $count"     # after procsub: 2

Same two lines, same loop body, different answer. The same page notes one escape hatch: with the lastpipe option on and job control off, “the last element of a pipeline may be run by the shell process.” Process substitution is the version that works without remembering a setting.

Loading lines into an array

When the whole list is needed at once, mapfile -t items < list.txt reads each line into its own array element, and -t strips the trailing newline. A two-line file holding alpha and beta gamma gave an array of length 2, and the quoted "${items[@]}" loop printed both lines whole.

Skipping and stopping

continue and break

The manual names the break and continue builtins as the tools “to control loop execution.” One loop with both:

for i in {1..10}; do
  (( i % 2 == 0 )) && continue
  (( i > 7 )) && break
  printf '%s ' "$i"
done

Output: 1 3 5 7

Even numbers are skipped by continue. At 9, the second test fires and break ends the loop, so 9 never prints. Both accept a number for nested loops: break 2 leaves two levels at once.

What the loop returns

A detail that matters in scripts using set -e or checking $?: the manual says a word-list loop’s return status “is the exit status of the last command that executes,” and if the list is empty, no commands run and the status is zero. An empty loop counts as success.

Scattered old black and white photographs

A real job: bulk renaming

Changing every .jpeg to .jpg

Here is the kind of task loops exist for. Two files, a.jpeg and b c.jpeg:

for f in *.jpeg; do
  mv -- "$f" "${f%.jpeg}.jpg"
done
ls
a.jpg
b c.jpg

Three details carry the weight. The glob keeps the space in b c.jpeg intact. "${f%.jpeg}" is parameter expansion that strips the shortest match of .jpeg from the end, so only the extension changes. And -- tells mv that everything after it is a filename, so a file named -rf.jpeg would be renamed rather than read as options.

Dry run first

Before running any loop that moves or deletes, swap the command for echo:

for f in *.jpeg; do echo mv -- "$f" "${f%.jpeg}.jpg"; done

It prints every command that would run without running any of them. Reading that list takes ten seconds. Restoring a folder of misnamed photos from backup takes considerably longer, assuming the backup exists.

The short version to keep

Glob instead of parsing ls. Quote every variable. Use "${array[@]}" with the quotes. Read files with while IFS= read -r. Count with ((…)) when the limit is in a variable. Most broken shell loops in the wild break one of those five, and the shell never warns about any of them.

Sources

  • GNU Bash Reference Manual, “Looping Constructs”: https://www.gnu.org/software/bash/manual/html_node/Looping-Constructs.html
  • GNU Bash Reference Manual, “Brace Expansion”: https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html
  • GNU Bash Reference Manual, “The Shopt Builtin”: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
  • GNU Bash Reference Manual, “Arrays”: https://www.gnu.org/software/bash/manual/html_node/Arrays.html
  • GNU Bash Reference Manual, “Pipelines”: https://www.gnu.org/software/bash/manual/html_node/Pipelines.html
  • GNU Bash Reference Manual, “Bash Builtin Commands”: https://www.gnu.org/software/bash/manual/html_node/Bash-Builtins.html
  • Greg’s Wiki, “Bash Pitfalls”: https://mywiki.wooledge.org/BashPitfalls

820 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *