How to Delete Fully Merged Branches
In a hurry? Watch our brief 1-minute vertical video that summarizes the info below.
Over time, your local repository can get cluttered with old branches. To keep things tidy, it's a good practice to delete branches that have been fully merged into your main branch.
Deleting All Merged Branches at Once
First, make sure you are on your main branch:
$ git checkout main
Then, you can run this command to find and delete all local branches that have been merged into main:
$ git branch --merged | egrep -v "(^\*|main|dev)" | xargs git branch -d
Let's break down this command:
git branch --merged: This lists all branches that have been fully merged into your current branch (which should bemain).egrep -v "(^\*|main|dev)": This filters the list. The-vflag inverts the match, so it removes the current branch (*), themainbranch, and adevbranch from the list. You should adjust this part to fit your branching workflow, protecting any other long-running branches you might have.xargs git branch -d: This takes the filtered list of branches and, for each one, runs thegit branch -dcommand to delete it.
Deleting a Single Branch
If you just want to delete a single local branch, you can use the -d (or --delete) flag:
$ git branch -d feature/new-login
This is a "safe" operation: Git will prevent you from deleting a branch if it has changes that haven't been merged yet.
To force the deletion of a branch, you can use the -D flag (a capital D). Be careful, as this will discard any unmerged work on that branch.
$ git branch -D feature/new-login
The Git Cheat Sheet
No need to remember all those commands and parameters: get our popular "Git Cheat Sheet" - for free!
Deleting Remote Branches
Keep in mind that these commands only delete local branches. To delete a branch from a remote repository, you need to use the git push command with the --delete flag:
$ git push origin --delete feature/new-login
Tip
Cleaning Up Branches in Tower
The Tower Git client offers a dedicated "Branches Review" feature. You can filter your branches to show only the "Fully Merged" ones and delete them with a single click.
Learn More
- Check out the chapter on Managing Branches in our free online book
Get our popular Git Cheat Sheet for free!
You'll find the most important commands on the front and helpful best practice tips on the back. Over 100,000 developers have downloaded it to make Git a little bit easier.
About Us
As the makers of Tower, the best Git client for Mac and Windows, we help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Ebay get the most out of Git.
Just like with Tower, our mission with this platform is to help people become better professionals.
That's why we provide our guides, videos, and cheat sheets (about version control with Git and lots of other topics) for free.