ls – Argument List Too Long for ls Command

argumentsls

I get the following error when trying to ls *.txt | wc -l a directory that contains many files:

-bash: /bin/ls: Argument list too long

Does the threshold of this "Argument list" dependent on distro or computer's spec? Usually, I'd pipe the result of such big result to some other commands (wc -l for example), so I'm not concerned with limits of the terminal.

Best Answer

Your error message argument list too long comes from the ***** of ls *.txt.

This limit is a safety for both binary programs and your Kernel. See ARG_MAX, maximum length of arguments for a new process for more information about it, and how it's used and computed.

There is no such limit on pipe size. So you can simply issue this command:

find -type f -name '*.txt'  | wc -l

NB: On modern Linux, weird characters in filenames (like newlines) will be escaped with tools like ls or find, but still displayed from *****. If you are on an old Unix, you'll need this command

find -type f -name '*.txt' -exec echo \;  | wc -l

NB2: I was wondering how one can create a file with a newline in its name. It's not that hard, once you know the trick:

touch "hello
world"
Related Question