Incorrect Quoting in Trap Commands Medium

The issue with using double quotes in trap commands is that it can cause the variables and commands to expand immediately, rather than when the trap is executed. This can lead to unexpected behavior, as the values may not be what you expect at the time the trap is triggered. To avoid this, use single quotes to prevent the expansion until the trap is executed.

Detector ID
shell/incorrect-quoting-in-trap-commands@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-
Tags
-

Noncompliant example

1
2# Noncompliant: Double quotes cause immediate expansion of the date command.
3trap "echo \"Script finished at $(date)\"" EXIT

Compliant example

1
2# Compliant: Single quotes delay expansion until the `trap` is triggered
3trap 'echo "Script finished at $(date)"' EXIT