---
title: Do not use expanding double quotes in trap handler actions
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Do not use expanding double quotes in trap handler actions
---

# Do not use expanding double quotes in trap handler actions

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ().
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

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

**Language:** Bash

**Severity:** Warning

**Category:** Security

**CWE**: [116](https://cwe.mitre.org/data/definitions/116.html)

**Related CWEs**:

- [117](https://cwe.mitre.org/data/definitions/117.html)
- [838](https://cwe.mitre.org/data/definitions/838.html)

## Description{% #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{% #non-compliant-code-examples %}

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

## Compliant Code Examples{% #compliant-code-examples %}

```bash
#!/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
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 