Using bash, how can one get the number of files in a folder, excluding directories from a shell script without the interpreter complaining?
With the help of a friend
The most straightforward, reliable way I can think of is using the find
command to create a reliably countable output.
Counting characters output of find
with wc
:
find . -maxdepth 1 -type f -printf '.' | wc --char
or string length of the find
output:
a=$(find . -maxdepth 1 -type f -printf '.')
echo ${#a}
or using find
output to populate an arithmetic expression:
echo $(($(find . -maxdepth 1 -type f -printf '+1')))
Get rid of the quotes. The shell is treating them like one file, so it's looking for "ls -l".
Simple efficient method:
#!/bin/bash
RES=$(find ${SOURCE} -type f | wc -l)
Here's one way you could do it as a function. Note: you can pass this example, dirs for (directory count), files for files count or "all" for count of everything in a directory. Does not traverse tree as we aren't looking to do that.
function get_counts_dir() {
# -- handle inputs (e.g. get_counts_dir "files" /path/to/folder)
[[ -z "${1,,}" ]] && type="files" || type="${1,,}"
[[ -z "${2,,}" ]] && dir="$(pwd)" || dir="${2,,}"
shopt -s nullglob
PWD=$(pwd)
cd ${dir}
numfiles=(*)
numfiles=${#numfiles[@]}
numdirs=(*/)
numdirs=${#numdirs[@]}
# -- handle input types files/dirs/or both
result=0
case "${type,,}" in
"files")
result=$((( numfiles -= numdirs )))
;;
"dirs")
result=${numdirs}
;;
*) # -- returns all files/dirs
result=${numfiles}
;;
esac
cd ${PWD}
shopt -u nullglob
# -- return result --
[[ -z ${result} ]] && echo 0 || echo ${result}
}
Examples of using the function :
folder="/home"
get_counts_dir "files" "${folder}"
get_counts_dir "dirs" "${folder}"
get_counts_dir "both" "${folder}"
Will print something like :
2
4
6