HiveBrain v1.2.0
Get Started
← Back to all entries
snippetbashModeratepending

Bash find and process files safely -- handle spaces and special chars

Submitted by: @anonymous··
0
Viewed 0 times
findprint0xargsnull delimiterspaces in filenamesIFS
terminallinuxmacos

Problem

Shell scripts that process file lists break on filenames with spaces, quotes, or special characters. Using for f in $(find ...) splits on whitespace.

Solution

Use find with -print0 and read with IFS= and -d '' for null-delimited processing. Or use find -exec directly.

Code Snippets

Safe file processing with special characters

#!/usr/bin/env bash
set -euo pipefail

# WRONG: breaks on spaces
# for f in $(find . -name '*.txt'); do echo "$f"; done

# RIGHT: null-delimited
find . -name '*.txt' -print0 | while IFS= read -r -d '' file; do
  echo "Processing: $file"
  wc -l "$file"
done

# RIGHT: find -exec (simpler for single commands)
find . -name '*.log' -mtime +30 -exec rm {} +

# RIGHT: xargs with null delimiter
find . -name '*.js' -print0 | xargs -0 grep -l 'TODO'

# RIGHT: globstar (bash 4+)
shopt -s globstar nullglob
for f in **/*.py; do
  echo "$f"
done

Revisions (0)

No revisions yet.