Delete local Git branches that are already merged
Clean up merged local branches safely, excluding main, master, develop and the current branch.
- Bash
- GreenSnippets
- MIT
git fetch --prune
git branch --merged \
| grep -Ev '^\*|^\s*(main|master|develop)$' \
| xargs -r git branch -dHow it works
git branch --merged lists branches whose commits are already in the current branch. The filter protects the branches you never want to delete, and -d (lowercase) refuses to delete anything unmerged. Run it from an up-to-date main.
Preview first by replacing git branch -d with echo. Squash-merged branches do not appear as "merged", so they need manual review. This command has been reviewed but not run through an automated test.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- Bash
Parse command-line flags with getopts
Handle -v, -o FILE and -h in a bash script with getopts and a usage message.
- Python Tested
Command-line tool skeleton with argparse
A small CLI with a positional argument, flags, a main function and proper exit codes.
- Bash
Timestamped tar.gz backup that keeps the newest N
Archive a directory with a sortable timestamp and delete older backups beyond a retention count.
- Bash
Safe header for Bash scripts
Fail fast on errors, unset variables and broken pipes, and clean up temp files with a trap.

