10.4. Counting Files in the Current Directory

To determine how many files there are in the current directory, put in ls -1 | wc -l. This uses wc to do a count of the number of lines (-l) in the output of ls -1. Note that we're using the numeral one (1) as the option to ls. It doesn't count dotfiles. Please note that ls -l (that's an "L" rather than a "1" as in the previous examples) which I used in previous versions of this HOWTO will actually give you a file count one greater than the actual count because the first line output by ls -l is a "total", a count of the number of KB used by the files listed. Thanks to Kam Nejad for this point.

If you want to count only files and NOT include symbolic links (just an example of what else you could do), you could use ls -l | grep -v ^l | wc -l (that's an "L" not a "1" this time, we want a "long" listing here). grep checks for any line beginning with "l" (indicating a link), and discards that line (-v).

Relative speed: "ls -1 /usr/bin/ | wc -l" takes about 0.040 seconds on an unloaded 800MHz Celeron. "ls -l /usr/bin/ | grep -v ^l | wc -l" takes about 0.170 seconds.