How can I create a bash script to count the number of files in a directory using a loop.
The script should take a target directory and output: Number of files in ::
How can I create a bash script to count the number of files in a directory using a loop.
The script should take a target directory and output: Number of files in ::
#!/bin/bash
counter=0
if [ ! -d "$1" ]
then
printf "%s\n" " $1 is not a directory"
exit 0
fi
directory="$1"
number="${directory##*/}"
number=${#number}
if [ $number -gt 0 ]
then
directory="$directory/"
fi
for line in ${directory}*
do
if [ -d "$line" ]
then
continue
else
counter=$(( $counter + 1))
fi
done
printf "%s\n" "Number of files in $directory :: $counter"
I would use (GNU) find
and wc
:
find /path/to/dir -maxdepth 1 -type f -printf '.' | wc -c
The above find
command prints a dot for every file in the directory and wc -c
counts those dots. This would work well with any kind of special character (including whitespaces and newlines) in the filenames.
You don't really need a loop. The following will count the files in a directory:
files=($(ls $1))
echo ${#files[@]}