Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

count=`ls -1 *.jpg 2>/dev/null | wc -l`
if [ $count != 0 ]
echo jpg files found: $count ; jpg="yes"

Considering file extensions jpg, png, bmp, raw and others, should I use a while cycle to do this?

share|improve this question

3 Answers 3

up vote 4 down vote accepted

I'd suggest a different approach, avoiding the possible word-splitting issues of ls


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


You can loop over the files array with any other commands you want to perform on the files of each particular extension.

share|improve this answer
@1_CR oops thank you - must have brace expansions on the brain! will correct above –  steeldriver Jul 26 '14 at 21:37

My approach would be:

  1. List all files in the directory
  2. Extract their extension
  3. Sort the result
  4. Count the occurrences of each extension

Sort of like this:

ls | awk -F . '{print $NF}' | sort | uniq -c | awk '{print $2,$1}'
share|improve this answer
mhmh... later should I filter each extension found for do an action for it? –  watchmansky Jul 26 '14 at 19:24
It depends on what you want to do in the end. Can you give more information? –  groxxda Jul 26 '14 at 19:25
My goal: a script that process each extension file (only image file) changing the size from input user data. So, I start from how many jpg files there're, next png, etc. –  watchmansky Jul 26 '14 at 19:27
steeldrivers solution may be more appropriate then. –  groxxda Jul 26 '14 at 19:30

Maybe it can get shorter

exts=( *.jpg *.png *.gif ); printf "There are ${#exts[@]}" extensions;
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.