# Bash Quick Loops

one-line `for` loops and the safer `while read` pattern, for renaming files, checking URLs and retrying failed commands. you don't need a whole script — most of the ones I run are one-liners right in the terminal.

## the one-liner for loop template

```bash
for f in *.txt; do SOMETHING "$f"; done
```

that's it. replace SOMETHING and go.

## renaming files in a loop with ${f%.txt}

change extensions:

```bash
for f in *.txt; do mv "$f" "${f%.txt}.md"; done
```

the `${f%.txt}` bit strips the suffix — see [Bash Variable Tricks](/articles/bash-variable-tricks) if that looks weird.

add a prefix:

```bash
for f in *.jpg; do mv "$f" "thumb_$f"; done
```

## looping over {1..10} and {dev,staging,prod}

combine with [Bash Brace Expansion](/articles/bash-brace-expansion) for generated lists:

```bash
for i in {1..10}; do echo "item $i"; done

for env in {dev,staging,prod}; do ./deploy.sh "$env"; done
```

server names:

```bash
for h in web0{1..5}; do ssh "$h" uptime; done
# hits web01 through web05
```

## looping over command output with $( )

```bash
for pid in $(pgrep nginx); do echo "nginx: $pid"; done
```

works fine for simple stuff. BUT if filenames have spaces this approach breaks. for that use the safe version:

## while read -r — the safe way with spaces in filenames

```bash
find . -name "*.log" | while read -r f; do
    gzip "$f"
done
```

`-r` prevents backslash weirdness. always use it with `read`.

## real loops: health checks, sed across files, retries

check if sites are up:

```bash
for url in google.com github.com mysite.com; do
    curl -so /dev/null -w "%{http_code} $url\n" "https://$url"
done
```

find and replace across files:

```bash
for f in *.html; do sed -i 's/old/new/g' "$f"; done
```

retry something until it works:

```bash
for i in {1..5}; do
    curl -sf localhost:8080/health && break
    echo "attempt $i failed"
    sleep 2
done
```

## xargs instead of a loop, and -P for parallelism

sometimes cleaner than a loop, and `-P` gives you parallelism for free:

```bash
find . -name "*.tmp" | xargs rm
find . -name "*.jpg" | xargs -P4 -I{} convert {} -resize 50% {}
```

see [Bash Process Tricks](/articles/bash-process-tricks) for more parallel stuff.

## the footgun — looping over ls output

don't do `for f in $(ls)`. it breaks on spaces, newlines, all kinds of stuff. just use `for f in *` or `find` with `while read`. [this page explains why](https://mywiki.wooledge.org/ParsingLs).

---

see also: [Bash Variable Tricks](/articles/bash-variable-tricks), [Bash Brace Expansion](/articles/bash-brace-expansion), [Bash Process Tricks](/articles/bash-process-tricks), [Bash Keyboard Shortcuts](/articles/bash-keyboard-shortcuts)

[bashfaq on reading files](https://mywiki.wooledge.org/BashFAQ/001) — worth reading if you do a lot of text processing
