---
title: "How to loop over files with spaces in their names in Bash"
description: "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."
url: https://www.danny.engineering/answer/bash/how-to-loop-over-files-with-spaces-in-their-names-in-bash
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:25:00.000Z
tags: ["Bash"]
---

# How to loop over files with spaces in their names in Bash

## 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 ''`.


```bash
# One directory
for file in ./*.jpg; do
  echo "Processing: $file"
done

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


## Why it happens


The broken version usually looks like this:


```bash
for file in $(ls *.jpg); do
  rm "$file"
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.


```bash
shopt -s nullglob   # if nothing matches, loop zero times instead of once

for file in ./photos/*.jpg; do
  mv -- "$file" "./archive/$(basename -- "$file")"
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`:


```bash
shopt -s globstar nullglob
for file in ./src/**/*.css; do
  echo "$file"
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.


```bash
while IFS= read -r -d '' file; do
  printf 'Found: %s\n' "$file"
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:


```bash
count=0
while IFS= read -r -d '' file; do
  count=$((count + 1))
done < <(find . -type f -print0)
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:


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


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


```bash
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 ''`:


```bash
mapfile -d '' files < <(find . -type f -name '*.md' -print0)
echo "Found ${#files[@]} files"
for file in "${files[@]}"; do
  wc -w "$file"
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.

## Related reading

- [Bash Reference Manual: Filename Expansion](https://www.gnu.org/software/bash/manual/html_node/Filename-Expansion.html)
- [GNU findutils: Safe File Name Handling](https://www.gnu.org/software/findutils/manual/html_node/find_html/Safe-File-Name-Handling.html)
