HOWTO Loop over multiple files using Bash

HOWTO Loop over multiple files using Bash

From Consultancy.EdVoncken.NET

Jump to: navigation, search

[edit] Problem

You wish to loop over multiple files, but there may be no files to process.

[edit] Solution

Use the following construct:

 shopt -s nullglob
 cd /tmp
 for file in *.ext;
 do
   echo "Processing $file"
 done

This will process each file in turn. If no files match the specification, the for-loop is not executed.

[edit] Discussion

The "shopt -s nullglob" is essential here. Without the "nullglob" shell option, the script will simply return the literal string (file="*.ext") if there are no files matching the pattern.

This is obviously not what we want. By setting the "nullglob" shell option, the expression will return an empty string if there are no files matching the glob pattern.

It is tempting to invoke another program (/bin/ls):

 cd /tmp
 for file in `/bin/ls -1 *.ext 2>/dev/null`;
 do
   echo "Processing $file"
 done

This solution has problems with filenames containing whitespace, and should be avoided.