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"
doneUsing For Loop with Find
for file in $(find /path/to/directory -type f); do
echo "$file"
doneWARNING
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"
doneUsing Find with Null Delimiter (Safest)
find /path/to/directory -type f -print0 | while IFS= read -r -d '' file; do
echo "$file"
doneThis 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 nullglobThe 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"
doneDetails
| Method | Handles Spaces | Recursive | Notes |
|---|---|---|---|
| For + wildcard | Yes | No | Simple, most common |
| For + find | No | Yes | Avoid for filenames spaces |
| While + find | Yes | Yes | Recommended |
| Find + print0 | Yes | Yes | Safest for special chars |
Appendix
Note created on 2025-12-23 and last modified on 2025-12-23.
See Also
Backlinks
(c) No Clocks, LLC | 2025