Jordan Savant # Software Engineer

# The script accepts a directory and produces output that tells how many regular files, directories, and symbolic links are in the directory (exclude subdirectories).
# The words in the output are singular or plural depending on the count (e.g. 1 link, 2 links).  Make sure the directory exists.
# Use the current directory if none was provided.
# Print out a "Usage" message if the user gave more than one argument.

# Syntax:   countfiles.sh directory

#!/bin/bash

#usage
directory=$1
[ $# -eq 0 ] && directory=$PWD
[ $# -gt 1 ] && { echo "Usage: countfiles.sh requires one directory as a parameter."; exit 1; }

dirs=0;files=0;links=0
# take directory parameter and check if it exists
# $0 is the directory
[ -d $directory ] || { echo "Directory specified either does not exist or is of a different file type."; exit 1; }

# loop through files in directory
for file in $directory/*;
do
    [ -d "$file" ] && dirs=`expr $dirs + 1`
    [ -f "$file" ] && files=`expr $files + 1`
    [ -h "$file" ] && links=`expr $links + 1`
done

echo "Directory $directory contains:";
if [ $dirs -eq 1 ]; then
    echo "$dirs directory"
else
    echo "$dirs directories"
fi
if [ $files -eq 1 ]; then
    echo "$files file"
else
    echo "$files files"
fi
if [ $links -eq 1 ]; then
    echo "$links symbolic link"
else
    echo "$links symbolic links"
fi

exit 0