Why does using a wildcard to halve the number of arguments fail with "Argument list too long"?

时间:2019-01-18 18:18:24

标签: bash shell unix arguments

$ ls  <path>/ | wc -l
52137

A full directory listing works. But attempting to shorten the number of files, I get:

$ ls <path>/*horiz | wc -l
-bash: /bin/ls: Argument list too long
0  

Why?

2 个答案:

答案 0 :(得分:1)

Because with ls <path>/, you are asking ls to list the files of <path>. But with ls <path>/*horiz, the shell is expanding the asterisk into the actual list of files, like

ls <path>/<prefix1>horiz <path>/<prefix2>horiz ... <path>/<prefixN>horiz

but that list is too long for a single shell line, so it gaves you the error.

答案 1 :(得分:1)

This has one argument, the directory name, which ls loops over internally:

ls <path>/

Note however that this is not one argument:

ls <path>/*horiz

Here, the shell itself expands <path>/*horiz into all the files that match, and then launches ls with that list of matches.

You might try something like this:

ls <path>/ | grep -c 'horiz$'