How to Delete Local Branches Already Merged into Master in Git

When managing projects with Git, you often need to delete local branches that have already been merged into the master branch. This helps keep your project repository tidy and clears out development branches that are no longer needed. Here are some simple steps to achieve this.

Confirm the Current Branch

First, make sure you are not on the local branch you want to delete. If you are, switch to another branch first:

Terminal window
git checkout master

List Merged Branches

Run the following command to view and save the list of branches already merged into master:

Terminal window
git branch --merged | grep -v "\*" | grep -v "master" > git.txt

This will list all branches merged into master. Ensure the branch you want to delete is in the list.

Delete Local Branches (Proceed with Caution!!!)

Once you’ve confirmed that git.txt contains only branches you want to delete that have been merged into master, you can delete them:

Terminal window
xargs git branch -d < git.txt

Delete Remote Branches (Proceed with Caution!!!)

After deleting local branches, you may also need to delete the corresponding remote branches:

Terminal window
xargs git push origin --delete < git.txt

git-sweep

If you don’t want to run these commands manually, there’s a ready-made tool:

git-sweep

It also has more features — this is just a reference.

Summary

With these simple steps, you can easily delete local branches merged into the master branch and keep your project repository clean and organized.