Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

If I do ls -1 target_dir | wc -l, I get a count of files in a directory. I find this a bit cumbersome. Is there a more elegant or succinct way?

share|improve this question
You don't need the "-1" when piping to wc. –  Steve May 1 '14 at 18:18
ls already gives the total count, so how about ls -l | head -1? Make it an alias if you want something shorter. –  Daniel Wagner May 2 '14 at 4:19
@DanielWagner The "total: nnn" output by ls -l indicates the total size of the files, not the number of files. –  David Richerby May 2 '14 at 7:58
Keep in mind that ls | wc -l will give you the wrong count if any file names contain newlines. –  chepner May 2 '14 at 19:29

5 Answers 5

Assuming bash 4+ (which any supported version of Ubuntu has):

num_files() (
    shopt -s nullglob
    cd -P -- "${1-.}" || return
    set -- *
    echo "$#"

Call it as num_files [dir]. dir is optional, otherwise it uses the current directory. Your original version does not count hidden files, so neither does this. If you want that, shopt -s dotglob before set -- *.

Your original example counts not only regular files, but also directories and other devices -- if you really only want regular files (including symlinks to regular files), you will need to check them:

num_files() (
    local count=0

    shopt -s nullglob
    cd -P -- "${1-.}" || return
    for file in *; do
        [[ -f $file ]] && let count++
    echo "$count"

If you have GNU find, something like this is also an option (note that this includes hidden files, which your original command did not do):

num_files() {
    find "${1-.}" -maxdepth 1 -type f -printf x | wc -c

(change -type to -xtype if you also want to count symlinks to regular files).

share|improve this answer
Won't set fail if there are very many files? I think you might have to use xargs and some summing code to make that work in the general case. –  l0b0 May 1 '14 at 11:31
Also shopt -s dotglob if you want files starting with . to be counted –  Maria Tidal Tug May 1 '14 at 15:19
@l0b0 I don't think set will fail under these circumstances, since we're not actually doing an exec. To wit, on my system, getconf ARG_MAX yields 262144, but if I do test_arg_max() { set -- {1..262145}; echo $#; }; test_arg_max, it happily replies 262145. –  kojiro May 1 '14 at 17:52
@DavidRicherby -maxdepth is not POSIX. –  Chris Down May 1 '14 at 21:27
@MichaelMartinez Writing obvious code is not a substitute for writing correct code. –  Chris Down May 2 '14 at 5:51

f=(target_dir/*);echo ${#f[*]}

works correctly for file with spaces, newlines, etc. in the name.

share|improve this answer
can you provide some context? Should this go in a bash script? –  codecowboy May 2 '14 at 7:47
it could. you could also put it directly in the shell. that version assumed you wanted the current directory; i've edited it so it's closer to your question. basically it creates a shell array variable containing all the files in the directory, then prints the count of that array. should work in any shell with arrays -- bash, ksh, zsh, etc. -- but probably not plain sh/ash/dash. –  Aaron Davies May 2 '14 at 15:40

ls is multi-columns only if it outputs directly to a terminal, you can remove the "-1" option, You can remove the wc "-l" option, only read the first value (lazy solution, not to be used for legual evidences, criminal investigations, mission critical, tactical ops..).

ls target | wc 
share|improve this answer
This fail for filenames containing newlines. –  l0b0 May 1 '14 at 11:29
@Emmanuel You'll need to parse the result of your wc to get the number of files in even the trivial case, so how is this even a solution? –  l0b0 May 2 '14 at 7:22
@Emmanuel This can fail if target is a glob which, when expanded, includes some things that start with hyphens. For example, make a new directory, go into it and do touch -- {1,2,3,-a}.txt && ls *|wc (NB: use rm -- *.txt to delete those files.) –  David Richerby May 2 '14 at 7:51
Did you mean wc -l? Otherwise you get newline, word, and byte counts of the ls output. That is what David Richerby said: You have to parse it again. –  erik May 2 '14 at 20:55
@erik I ment wc with no argument you don't need to parse if your brain knows that the first argument is newline. –  Emmanuel May 2 '14 at 22:06

If it's succinctness you're after (rather than exact correctness when dealing with files with newlines in their names, etc.), I recommend just aliasing wc -l to lc ("line count"):

$ alias lc='wc -l'
$ ls target_dir|lc

As others have noted, you don't need the -1 option to ls, since it's automatic when ls is writing to a pipe. (Unless you have ls aliased to always use column mode. I've seen that before, but not very often.)

An lc alias is quite handy in general, and for this question, if you look at the "count the current directory" case, ls|lc is about as succinct as you can get.

share|improve this answer

So far Aaron's is the only approach more succinct than your own. A more correct version of your approach might look like:

ls -aR1q | grep -cv '^\./\|/$\|^$'

That recursively lists all files - not directories - one per line including .dotfiles beneath the current directory using shell globs as necessary to replace non-printable characters. grep filters out any parent directory listings or .. or */ or blank lines - so there should only be one line per file - the total count of which grep returns to you. If you want child directories included as well do:

ls -aR1q | grep -cv '^\.\{1,2\}/\|^$'

Remove the -R in either case if you do not want recursive results.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.