For the purpose of testing, I'd like count how many images files are inside a directory, separating each image file type by file extension (jpg="yes". This because later it will be useful for another script that will execute an action on each file extension). Can I use something like the following for only JPEG files?
jpg=""
count=`ls -1 *.jpg 2>/dev/null | wc -l`
if [ $count != 0 ]
then
echo jpg files found: $count ; jpg="yes"
fi
Considering file extensions jpg, png, bmp, raw and others, should I use a while
cycle to do this?
Best Answer
I'd suggest a different approach, avoiding the possible word-splitting issues of
ls
You can loop over the
files
array with any other commands you want to perform on the files of each particular extension.More portably - or for shells that don't provide arrays explicitly - you could re-use the shell's positional parameter array i.e.
and then replace
${#files[@]}
and${files[@]}
with$#
and"$@"