Glob-based Iteration High

Iterating over 'ls' output can lead to issues with filenames containing spaces, special characters, or glob patterns, potentially causing incorrect file processing. To fix this, use shell globs directly in for loops to safely iterate over files.

Detector ID
shell/glob-based-iteration@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-
Tags
-

Noncompliant example

1
2# Noncompliant: This will fail for filenames with spaces or special characters.
3for img in $(ls *.jpg)
4do
5    convert "$img" "${img%.jpg}.png"
6done

Compliant example

1
2# Compliant: This correctly handles all filenames, including those with spaces or special characters.
3shopt -s nullglob
4for img in *.jpg
5do
6    [[ -e "$img" ]] || continue
7    convert "$img" "${img%.jpg}.png"
8done