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

snippet
#!/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