You can count just the files in a specified directory using
ls -1F $dir_path | grep -v / | wc -l
where:
ls -1F $dir_path
lists the files and folders within $dir_path
-- -1
list one file per line
-- -F
append indicator to entries (one of */=>@|)
-- $dir_path
holds the argument passed to your script
grep -v /
filters out the directories (if any)
wc -l
counts the remaining lines which represents the files
In case you'd like to include hidden files - add the -A
flag to ls
.
The (basic) final script would look like so:
#!/bin/bash
# Set dir_path to current directory to support execution without arguments
dir_path="."
if [ $# -eq 1 ]; then
dir_path="$1"
fi
num_of_files=$(ls -1F $dir_path | grep -v / | wc -l)
echo "Directory ${dir_path} have ${num_of_files} files."