Skip to content
shellhacks.dev
Command Line

Avoid Parsing ls Output in Shell Scripts

Do not loop over the output of ls in a script. File names with spaces or a newline split into pieces, while a glob such as ./* hands over each name whole.

1 min read
Summarize in AI

A loop over $(ls) works until the first file with a space in its name, and then it processes things that are not files.

Shell
touch "plain.txt" "two  spaces.txt"
touch $'new\nline.txt'
for f in $(ls); do echo "got: $f"; done
echo ---
for f in ./*; do printf 'got: %q\n' "$f"; done
Text
got: new
got: line.txt
got: plain.txt
got: two
got: spaces.txt
---
got: $'./new\nline.txt'
got: ./plain.txt
got: ./two\ \ spaces.txt

The shell splits the output of ls on whitespace, so each space and each newline starts a new word, and the loop sees six words for three files. A glob is expanded by the shell itself, one word per file, with no splitting. The Bash FAQ lists further problems, such as ls replacing unprintable characters with a question mark when its output is not a terminal. printf %q shows the names in a form that makes the odd ones visible.

A glob that matches nothing is left as the literal pattern unless nullglob is set, so test that a file exists before using it. A name beginning with a dash would be read as an option, so the ./ prefix matters. To select by age, size or type, use find with -print0 and read the result with read -d ''.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.