Bash

Recursive Directory Walker with Predicate

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use `find -print0` + `read -d ""` to safely iterate filenames that may contain spaces, newlines, or quotes. Standard bash for-loop over `find` output breaks on these.
Bash
Raw
# Process every .log file safely (handles spaces / newlines in names)
while IFS= read -r -d '' file; do
    echo "processing: $file"
    # gzip "$file"
done < <(find /var/log -type f -name "*.log" -print0)

# Same idea with a callback function
walk_files() {
    local root="$1" pattern="$2" callback="$3"
    while IFS= read -r -d '' f; do
        "$callback" "$f"
    done < <(find "$root" -type f -name "$pattern" -print0)
}

count_lines() { wc -l < "$1"; }
walk_files /var/log "*.log" count_lines
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.