Getting filename lists without ls

ls is a very useful command for getting listings, but it is often misused by being parsed in scripts to get filenames or file data from the output. The problem with this is that ls is designed for human users to read, not other programs.

You may have seen bad code like this on the web:

# Bad code$ grep pattern `ls`
$ for file in `ls` ; do grep pattern $file ; done

This fails as soon as there is a filename with any special characters in it, such as a space, an asterisk, or a semicolon:

$ ls -1
programming
recipes
file with spaces
file*
# Bad code$ grep pattern $(ls)
grep: file: No such file or directory
grep: with: No such file or directory
grep: spaces: No such file or directory

It is always better to use ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.