Iterating over Files

Overview

Common techniques for looping through files in a directory using Bash.

Code

Using For Loop with Wildcard

for file in /path/to/directory/*; do
    echo "$file"
done

Using For Loop with Find

for file in $(find /path/to/directory -type f); do
    echo "$file"
done

WARNING

This method will not handle filenames with spaces correctly.

Using While Loop with Find (Safe)

find /path/to/directory -type f | while read -r file; do
    echo "$file"
done

Using Find with Null Delimiter (Safest)

find /path/to/directory -type f -print0 | while IFS= read -r -d '' file; do
    echo "$file"
done

This handles filenames with spaces, newlines, and special characters.

Using Glob with Nullglob

shopt -s nullglob
for file in /path/to/directory/*.txt; do
    echo "$file"
done
shopt -u nullglob

The nullglob option prevents the loop from running if no files match.

Recursive Iteration

# using globstar (bash 4+)
shopt -s globstar
for file in /path/to/directory/**/*; do
    [ -f "$file" ] && echo "$file"
done
shopt -u globstar
 
# using find
find /path/to/directory -type f -name "*.txt" | while read -r file; do
    echo "$file"
done

Details

MethodHandles SpacesRecursiveNotes
For + wildcardYesNoSimple, most common
For + findNoYesAvoid for filenames spaces
While + findYesYesRecommended
Find + print0YesYesSafest for special chars

Appendix

Note created on 2025-12-23 and last modified on 2025-12-23.

See Also


(c) No Clocks, LLC | 2025