Bash Safe find with NUL-Delimited Paths

Enumerate and prune files with find -print0 and read -d '' so spaces, quotes, and newlines in filenames cannot break the script.

BashSecurity Boundaries

Code

bashsnippet
48 lines
#!/usr/bin/env bash
set -euo pipefail

root=${1:-.}
apply=${APPLY:-0}

if [[ ! -d "$root" ]]; then
    printf 'not a directory: %s\n' "$root" >&2
    exit 1
fi

if [[ "$root" == "/" ]]; then
    printf 'refusing to scan the filesystem root\n' >&2
    exit 1
fi

if [[ "$apply" != "0" && "$apply" != "1" ]]; then
    printf 'APPLY must be 0 or 1, got %s\n' "$apply" >&2
    exit 2
fi

printf 'log files (NUL-safe enumeration):\n'
while IFS= read -r -d '' file; do
    printf '  %q\n' "$file"
done < <(
    find "$root" \
        -type d -name .git -prune -o \
        -type f -name '*.log' -print0
)

found=0
while IFS= read -r -d '' file; do
    found=$((found + 1))
    if (( apply )); then
        printf 'removing %q\n' "$file"
        rm -f -- "$file"
    else
        printf 'would remove %q (set APPLY=1 to delete)\n' "$file"
    fi
done < <(
    find "$root" \
        -type d -name .git -prune -o \
        -type f -name '*.tmp' -mtime +7 -print0
)

if (( found == 0 )); then
    printf 'no temporary files older than 7 days under %s\n' "$root"
fi

How the snippet works

Strict mode (set -euo pipefail) makes failures loud — an unset variable or a failing pipeline stage aborts the script instead of being swallowed.

The work is delegated to find and rm, chained so each stage’s output feeds the next.

The script leans on parameter expansion 2 times, using forms like ${var:-default} so defaults, trimming, and casing happen inside the shell with no external tool.

The key statements, annotated

while IFS= read -r -d '' file; do
    printf '  %q\n' "$file"
while IFS= read -r -d '' file; do
    found=$((found + 1))

Interactive Tools for This Topic

FAQ

Does the script stop on the first error?
Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
Which external commands does the script rely on?
`find`, `rm` must be available on the PATH environment variable; everything else is shell built-in syntax.