Delete Merged Branches
You can delete the merged branches listed in the previous step using a loop in Bash or another scripting language. Below is an example Bash script to achieve this:
git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
Let’s break down this command:
- git branch –merged: Lists branches that have been merged.
- grep -v “\*”: Excludes the current branch from the list.
- xargs -n 1 git branch -d: Deletes each branch listed.
This script iterates over the list of merged branches (excluding the current branch) and deletes them one by one.
Bash Script to Delete Merged Branches
You can run the following script to delete all branches that have been merged, excluding main
and master
:
for branch in $(git branch --merged | grep -vE '^(main|master)$'); do
git branch -d $branch
done
How to Delete all Git Branches which have been Merged?
To delete Git branches that have been merged into the current branch, you can use a combination of git branch and git branch -d commands along with some scripting. Below is a step-by-step guide:
Table of Content
- Switch to the Branch You Want to Clean Up
- List Merged Branches
- Delete Merged Branches
- Force Delete (if necessary)
- Confirmation
- Additional Tips