Shell – Iterating over files in Bash and obtaining the index and the counts

shell-script

The proper way to iterate over files in a directory in Bash is using "for loop" and glob as following:

for f in *.jpg; do
    echo "- Processing file: $f"
done

But how can I retrieve the total count of the files and the current index of the loop interaction? I need the total count, not the cumulative count to show the progress.

Best Answer

I would store the list of files in an array, so that you don't have to read the file system twice, increasing performance and reducing potential race conditions. Then use another variable as the index.

files=(*.jpg)
total=${#files[@]}
i=0
for f in "${files[@]}"; do
    i=$(( i + 1 ))
    echo index $i
    echo total $total
    echo "- Processing file: $f"
done

Explanation

  • files=(*.jpg): store the glob into the array $files
  • total=${#files[@]}: read the total into $total
  • i=0: initialise $i to 0.
  • i=$(( i + 1 )): add 1 to $i each loop

This presumes that the "first" loop is 1. Depending on your opinion, you might want to start at 0 instead.

Related Question