Counting Files

In a script, how would I go about finding the number of files for the first parameter after my script name?

For instance, my script name is myscript.sh and the folder I am checking is not the current working directory, lets say it's folder1.

so I type myscript.sh folder1

This script below only works for current directory. Here is what I have so far

FILE=$1
count=0

for FILE in *
do
     if [ -f $FILE ]
     then
     count=`expr $count + 1`
     fi
done

echo "File Count: $count"

Thanks!

Hi.

With only a couple of modifications:

DIR=${1:-.}  # if $1 isn't given, use current directory (.)
count=0

[ ! -d $DIR ] && echo "No such directory." && exit 1

for FILE in $DIR/*  # Safer using a while loop, really!
do
     if [ -f "$FILE" ]
     then
     count=$((count + 1))
     fi
done

echo "File Count: $count"

1 Like

I think I tried everything in the world except $DIR/* , just the $DIR/ is what made the difference. Thank you so much!