I\'m learning bash scripting and have written a script to count the files and directories in the directory that is supplied as argument. I have it working one way which seem
To just solve the problem you can use:
FILECOUNT=$(find $LOCATION -type f | wc -l)
DIRCOUNT=$(find $LOCATION -type d | wc -l)
find
will look for all files (-type f
) or directories (-type d
) recursively under $LOCATION
; wc -l
will count the number of lines written to stdout in each case.
However if you want to learn, the bash script may be a better way. Some comments:
$LOCATION
only (not recursively under their subdirectories etc), you can use for item in $LOCATION/*
, where the *
will expand to the list of files/directories in the $LOCATION
directory. The missing *
is why your original script returns 0/1 (becasue the $LOCATION
directory itself is the only item counted).$LOCATION
is actually a directory with [ -d $LOCATION ]
.$(( ... ))
, for example FILECOUNT=$(( FILECOUNT + 1 ))
.find
with a loop.Example:
find $LOCATION | while read item; do
# use $item here...
done