How to count number of files and subdirectories with shellscript?
I suggest two changes: eliminate the unnecessary files
variable, and use a glob instead of parsing the output of ls
. Then use the -d
test to see if each directory entry is a directory (if it's not, assume it's a regular file, unless you really care about distinguishing named pipes, character devices, block devices, etc) and use the $((...))
expression for arithmetic.
echo "What absolute directory do you want to count?"read DIRcd "$DIR" || exitfile=0dir=0for d in *;do if [ -d "$d" ]; then dir=$((dir+1)) else file=$((file+1)) fidoneecho "Files $file"echo "Directories $dir"