Shell Script – Count Files in a Directory by Extension

filenamesshell-script

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

#!/bin/bash

shopt -s nullglob

for ext in jpg png gif; do 
  files=( *."$ext" )
  printf 'number of %s files: %d\n' "$ext" "${#files[@]}"

  # now we can loop over all the files having the current extension
  for f in "${files[@]}"; do
    # anything else you like with these files
    :
  done 

done

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.

set -- *."$ext"

and then replace ${#files[@]} and ${files[@]} with $# and "$@"