How to get the number of files in a folder as a variable?

ls -l | grep -v ^d | wc -l

One line.


How about:

count=$(find .. -maxdepth 1 -type f|wc -l)
echo $count
let count=count+1 # Increase by one, for the next file number
echo $count

Note that this solution is not efficient: it spawns sub shells for the find and wc commands, but it should work.


The quotes are causing the error messages.

To get a count of files in the directory:

shopt -s nullglob
numfiles=(*)
numfiles=${#numfiles[@]}

which creates an array and then replaces it with the count of its elements. This will include files and directories, but not dotfiles or . or .. or other dotted directories.

Use nullglob so an empty directory gives a count of 0 instead of 1.

You can instead use find -type f or you can count the directories and subtract:

# continuing from above
numdirs=(*/)
numdirs=${#numdirs[@]}
(( numfiles -= numdirs ))

Also see "How can I find the latest (newest, earliest, oldest) file in a directory?"

You can have as many spaces as you want inside an execution block. They often aid in readability. The only downside is that they make the file a little larger and may slow initial parsing (only) slightly. There are a few places that must have spaces (e.g. around [, [[, ], ]] and = in comparisons) and a few that must not (e.g. around = in an assignment.

Tags:

Shell

Bash