Or a better way would be to pass the path to the directory and then directly use ls with the passed in path. That way, there's no need to change the working directory by cd-ing into the passed-in directory.
Modifying Robs code slightly:
#function to display usage info
echo "Usage: $0 <path>"
echo -e "Example: $0 /home/"
# Ensure there is exactly one parameter
if [[ $# -ne 1 ]] ; then
echo "Error - requires a single parameter which"
echo "must be a path to a valid directory"
# Ensure the parameter is a valid directory
else if [[ ! -d $1 ]] ; then
echo "Error - $1 is NOT a directory!"
# Get the number of items in the passed in path
documentCount=$(ls $1 | wc -l)
echo "In directory: $1"
echo "Document Count = $documentCount"
if [ $documentCount -gt $control]
echo "File Count > $control"
echo "File Count < $control"
Also - using ls will list files and directories in the passed-in path.
So the documentCount is more of an itemCount than a documentCount.
If you want to use ls to determine the number of actual files in a directory - excluding any directories, you would need to use something like this in your script:
documentCount=$(ls -FL $1 | \grep -v '/$' | wc -l)
The -F parameter to ls causes ls to add a character to the end of each listing to determine each files type.
* at the end means an executable file
/ at the end means a directory
no extra character at the end denotes a normal, non-executable file
@ at the end, denotes a symbolic link
The -L parameter causes ls to dereference any symbolic links.
A symbolic link is like a shortcut - it can point to a file, or a directory.
With the -L parameter-
ls -FL $1
will dereference any sym-links it finds and then append a "/" at the end if the link points to a directory, or "*" if it's an executable file, or nothing if the link points to a normal, non-executable file.
That way if there are any symbolic links that point to directories in the listing - they will be excluded from our count of documents.
we pipe to
grep -v '/$'
to filter-out/remove the listings for directories (items with a / at the end).
The output from that is piped to
to yield a count of actual files.
Or alternatively, if you want to exclude symbolic links from the count, you could do this instead:
documentCount=$(ls -F | \grep -v '/$' | \grep -v '@$' | wc -l)
Either of those options would yield a more accurate count of the number of files in any given directory.
Or you could just use find:
documentCount=$(find $1 -maxdepth 1 -type f | wc -l)
Find automatically excludes symbolic links. And setting -maxdepth to 1 prevents find from recursing into any sub-directories and adding their contents to the count.