Find Loop Safety Medium

Iterating over 'find' output using 'for' loops can lead to issues with filenames containing spaces or special characters, potentially causing script errors or unexpected behavior. To fix this, use safer alternatives like 'find -exec' or 'while read' loops to properly handle all types of filenames.

Detector ID
shell/find-loop-safety@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-
Tags
-

Noncompliant example

1
2# Noncompliant: This will fail for filenames containing spaces or special characters.
3for file in $(find ./documents -type f -name "*.txt")
4do
5    echo "Processing: $file"
6    wc -l "$file"
7done

Compliant example

1
2# Compliant: This correctly handles filenames with spaces and special characters.
3find ./documents -type f -name "*.txt" -print0 | while IFS= read -r -d '' file
4do
5    echo "Processing: $file"
6    wc -l "$file"
7done