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_10for file in ./*.jpg; do_10 echo "Processing: $file"_10done_10_10# Recursive, safe for any file name_10while IFS= read -r -d '' file; do_10 echo "Processing: $file"_10done < <(find . -type f -name '*.jpg' -print0)
Why it happens
#The broken version usually looks like this:
_10for file in $(ls *.jpg); do_10 rm "$file"_10done
$(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.
_10shopt -s nullglob # if nothing matches, loop zero times instead of once_10_10for file in ./photos/*.jpg; do_10 mv -- "$file" "./archive/$(basename -- "$file")"_10done
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:
_10shopt -s globstar nullglob_10for file in ./src/**/*.css; do_10 echo "$file"_10done
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.
_10while IFS= read -r -d '' file; do_10 printf 'Found: %s\n' "$file"_10done < <(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:
_10count=0_10while IFS= read -r -d '' file; do_10 count=$((count + 1))_10done < <(find . -type f -print0)_10echo "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:
_10find . -type f -name '*.tmp' -exec rm -- {} +
You can also pair find -print0 with xargs -0:
_10find . -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 '':
_10mapfile -d '' files < <(find . -type f -name '*.md' -print0)_10echo "Found ${#files[@]} files"_10for file in "${files[@]}"; do_10 wc -w "$file"_10done
Common pitfalls
#- Forgetting to quote
"$file"inside the loop. The loop itself is safe, butrm $filewill still split the name. - Leaving out
IFS=or-rinread, which trims spaces at the ends of names and mangles backslashes. - Using
find | while readand expecting variables set in the loop to survive. Use process substitution instead. - Commands inside the loop that read standard input, such as
sshorffmpeg, can swallow the rest of the file list. Redirect their input with< /dev/null, or read the list from a different file descriptor. - Using
-print0with a tool that does not expect null-separated input. Only pair it withread -d '',xargs -0,mapfile -d ''or similar.
Related reading
#Was this resource helpful?