Script to Delete Merged Git Branches
After some weeks, a repository has many old branches that are already merged. This small script finds them and deletes them with the safe option -d, so unmerged work is never deleted.
#!/bin/sh
# Delete local branches already merged into main (keeps main)
git branch --merged main | grep -v -E '^\*|^ +main$' | while read -r branch; do
git branch -d "$branch"
done
Branches before the cleanup: feature-cart and old-fix are merged, but feature-search has a commit that is not in main.
Terminal output
$ git branch
feature-cart
feature-search
* main
old-fix
$ sh ../cleanup-branches.sh
Deleted branch feature-cart (was 40827b1).
Deleted branch old-fix (was 40827b1).
$ git branch
feature-search
* main
How it works
git branch --merged mainlists branches whose commits are all inmain.grep -vremoves the current branch (the star line) andmainfrom the list.- The loop runs
git branch -dfor each name. The capital-Dis not used, so unmerged branches are safe.
Note:
Remote branches are not touched. To clean the remote names, use git fetch --prune. See Git Branch.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |