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.
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"
7done1
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