Bash: Looping over Files and Folders

This article explains how to loop over files and folders in Linux.

Bash: Looping over Files and Folders

This is another article in the category of dumping my internal wiki to this blog.

Looping over Files and Directories with failglob

Dangerous Scripts

Looping through files

#!/bin/bash

for f in /path/to/files/*; do
  echo "Found file: $f"
done

or directories:

#!/bin/bash

for d in */ ; do
    echo "$d"
done

seems to be very easy.

Unfortunately, in the above code examples, if the paths are empty, the loop will execute exactly once, with f or d pointing to path/to/files/ or */ respectively. If this were to be followed by a rm, fun days would be ahead. Time to KKND!

Looking at the shopts man page offers the following two solutions.

shopt -s nullglob

nullgob allows filename patterns which match no files to expand to a null string, rather than themselves.

shopt -s failglob

With failglob, patterns which fail to match filenames during filename expansion result in an expansion error.

Correct Script

#!/bin/bash

shopt -s nullglob
for f in /path/to/files/*; do
  echo "Found file: $f"
done

References

shopts man page

Comments