If you want only regular files,
With GNU find
:
find . -maxdepth 1 -type f -printf . | wc -c
Other find
s:
find . ! -name . -prune -type f -print | grep -c /
(you don't want -print | wc -l
as that wouldn't work if there are file names with newline characters).
With zsh
:
files=(*(ND.)); echo $#files
With ls
:
ls -Anq | grep -c '^-'
To include symlinks to regular files, change -type f
to -xtype f
with GNU find
, or -exec test -f {} \;
with other find
s, or .
with -.
with zsh
, or add the -L
option to ls
. Note however that you may get false negatives in cases where the type of the target of the symlink can't be determined (for instance because it lies in a directory you don't have access to).
If you want any type of file (symlink, directory, pipes, devices...), not only regular one:
find . ! -name . -prune -printf . | wc -c
(change to -print | grep -c /
with non-GNU find
, (ND.)
to (ND)
with zsh
, grep -c '^-'
with wc -l
with ls
).
That will however not count .
or ..
(generally, one doesn't really care about those as they are always there) unless you replace -A
with -a
with ls
.
If you want all types of files except directories, Replace -type f
with ! -type d
(or ! -xtype d
to also exclude symlinks to directories), and with zsh
, replace .
with ^/
, and with ls
, replace grep -c '^-'
with grep -vc '^d'
.
If you want to exclude hidden files, add a ! -name '.*'
or with zsh
, remove the D
or with ls
, remove the A
.
find
not to descend into subdirectories. The-maxdepth 1
will do that for you. – Chris Davies Aug 01 '16 at 09:46find
-based answers do not explicitly increment a counter -- is that a requirement? – Jeff Schaller Aug 01 '16 at 15:41