More Bash answers

by Danny
Published 2 min read

Looping over ls output breaks on spaces in file names. Use globs, or find with -print0 and while read -d '', to handle any file name safely.

The short answer

#

Do not loop over the output of ls or an unquoted $(find ...). For files in one directory, loop over a glob and quote the variable. For recursive searches, have find separate names with null bytes and read them with while read -d ''.


_10
# One directory
_10
for file in ./*.jpg; do
_10
echo "Processing: $file"
_10
done
_10
_10
# Recursive, safe for any file name
_10
while IFS= read -r -d '' file; do
_10
echo "Processing: $file"
_10
done < <(find . -type f -name '*.jpg' -print0)

Why it happens

#

The broken version usually looks like this:


_10
for file in $(ls *.jpg); do
_10
rm "$file"
_10
done

$(ls ...) produces one long string. Because it is unquoted, Bash splits that string on spaces, tabs and newlines, so Holiday photo.jpg becomes two items: Holiday and photo.jpg. Neither exists, and the loop either fails or, worse, acts on the wrong files. Any word that contains *, ? or [ is also expanded as a pattern.

Quoting the substitution does not help either: "$(ls)" gives you a single item containing every name. There is no character you can split ls output on that is safe, because file names on Linux and macOS may contain any character except / and the null byte. That is why the safe approaches either avoid splitting completely (globs) or split on the null byte.

How to fix it

#

Use a glob for one directory

The shell expands a glob into a list of file names directly, with no splitting step, so spaces are preserved. Just quote the variable when you use it.


_10
shopt -s nullglob # if nothing matches, loop zero times instead of once
_10
_10
for file in ./photos/*.jpg; do
_10
mv -- "$file" "./archive/$(basename -- "$file")"
_10
done

Without nullglob, a pattern with no matches stays as the literal text ./photos/*.jpg, and the loop runs once with that string. The ./ prefix and -- stop names beginning with a hyphen being read as options.

For recursive globs, Bash 4 and later supports ** with globstar:


_10
shopt -s globstar nullglob
_10
for file in ./src/**/*.css; do
_10
echo "$file"
_10
done

macOS still ships Bash 3.2 as /bin/bash, which has no globstar. Install a newer Bash or use find.

Use find with -print0 and while read

-print0 ends each name with a null byte. read -d '' reads up to the next null byte, IFS= stops leading and trailing whitespace being trimmed, and -r stops backslashes being interpreted.


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

The < <(...) is process substitution. It feeds find's output into the loop without a pipe, so the loop runs in the current shell and any variables you set inside it are still there afterwards:


_10
count=0
_10
while IFS= read -r -d '' file; do
_10
count=$((count + 1))
_10
done < <(find . -type f -print0)
_10
echo "Total: $count"

With find ... | while read, the loop runs in a subshell and count would still be 0 at the end.

Let find run the command itself

If you only need to run one command per file, skip the loop. -exec ... + passes many names per call and handles any characters:


_10
find . -type f -name '*.tmp' -exec rm -- {} +

You can also pair find -print0 with xargs -0:


_10
find . -type f -name '*.png' -print0 | xargs -0 optipng

Read the names into an array

In Bash 4.4 and later, mapfile (also called readarray) accepts -d '':


_10
mapfile -d '' files < <(find . -type f -name '*.md' -print0)
_10
echo "Found ${#files[@]} files"
_10
for file in "${files[@]}"; do
_10
wc -w "$file"
_10
done

Common pitfalls

#
  • Forgetting to quote "$file" inside the loop. The loop itself is safe, but rm $file will still split the name.
  • Leaving out IFS= or -r in read, which trims spaces at the ends of names and mangles backslashes.
  • Using find | while read and expecting variables set in the loop to survive. Use process substitution instead.
  • Commands inside the loop that read standard input, such as ssh or ffmpeg, can swallow the rest of the file list. Redirect their input with < /dev/null, or read the list from a different file descriptor.
  • Using -print0 with a tool that does not expect null-separated input. Only pair it with read -d '', xargs -0, mapfile -d '' or similar.
#

Was this resource helpful?