Avoid Complex Logical Expressions Low

Combining '&&' and '||' operators without careful consideration can lead to unexpected behavior. For clear and predictable conditional logic, use if-then-else constructs. This prevents unintended execution of commands and improves code readability.

Detector ID
shell/avoid-complex-logical-expressions@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-
Tags
-

Noncompliant example

1
2# Noncompliant: This construct can lead to unexpected behavior.
3file="/path/to/important/file.txt"
4[[ -f $file ]] && echo "File exists: $file" > /dev/null || rm "$file"

Compliant example

1
2# Compliant: Using proper `if-then-else` construct for safety.
3file="/path/to/important/file.txt"
4if [[ -f $file ]]; then
5    echo "File exists: $file" > /dev/null
6else
7    rm "$file"
8fi