For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/bash-security/premature-expansion-in-trap.md. A documentation index is available at /llms.txt.

Do not use expanding double quotes in trap handler actions

This product is not supported for your selected Datadog site. ().

Metadata

ID: bash-security/premature-expansion-in-trap

Language: Bash

Severity: Warning

Category: Security

CWE: 116

Related CWEs:

Description

The trap builtin stores an action to run later. If that action is a double-quoted string, a parameter expansion, command substitution, and an arithmetic expansion run when trap is executed, not when the signal arrives. Values can be empty, stale, or wrong at exit time.

As an alternative, use a single-quoted handler so the shell parses expansions when the trap runs, not at registration. For example, it is better to use trap 'rm -f "$tmp"' EXIT instead of trap "rm -f $tmp" EXIT, and trap 'echo finished at $(date)' EXIT instead of trap "echo finished at $(date)" EXIT. If you need a literal dollar sign in the registered text, escape it inside double quotes (for example, trap "rm -f \$tmp" EXIT) or use single quotes and a different quoting strategy for the path.

Non-Compliant Code Examples

#!/bin/bash
trap "rm -f $tmp" EXIT
trap "echo ${HOME}" EXIT
trap "echo $(date)" EXIT
trap "v=$((1+1))" EXIT

Compliant Code Examples

#!/bin/bash
trap 'rm -f "$tmp"' EXIT
trap "literal only" EXIT
trap "rm -f \$tmp" EXIT
trap -p
trap cleanup INT TERM
trap /usr/local/bin/cleanup EXIT
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security