---
title: Avoid iteration over command output
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Avoid iteration over command output
---

# Avoid iteration over command output

{% 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-code-quality/avoid-iteration-over-command-output`

**Language:** Bash

**Severity:** Notice

**Category:** Code Style

## Description{% #description %}

A `for` loop over command output (e.g. `$(ls ...)` or backticks) splits on whitespace and can break on filenames with spaces or glob characters. Prefer globs (e.g. `for f in dir/*`) or `find` (e.g. `find . -name '*.mp3' -exec some command {} \;`) instead.

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

```bash
#!/bin/bash
for f in $(ls); do echo "$f"; done
for g in `ls -A`; do echo "$g"; done
for h in $(ls 2>/dev/null); do echo "$h"; done
```

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

```bash
#!/bin/bash
ls
for f in ./*.txt; do echo "$f"; done
find . -name '*.mp3' -exec some command {} \;
while IFS= read -r -d '' f; do echo "$f"; done < <(find . -maxdepth 1 -print0)
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 