Git Delete Merged Branches

Git Delete Merged Branches

As a part of standard development practice in GIT, we work on feature branches to push changes into the repository and merge it when the changes are tested and approved.

The old unwanted to branches keep building up over a period of time if they are not cleaned up. To take care of it we manually have to remove the branches which are merged into the master.

Not to mention you can delete any branch, whether merged or not.

Let’s start with the basic commands to delete branches first.

Git Delete Merged Branches

To delete a local branch which isn’t merged you can run the following:

$ git branch -D BRANCH_NAME

To delete a local branch which is merged run the following:

$ git branch -d BRANCH_NAME

Push the changes to remote using (delete from remote):

$ git push origin :BRANCH_NAME

Or for newer version of GIT you can use the following to push the changes to remote:

$ git push --delete origin BRANCH_NAME

That should be good enough for the basics of deleting the branch.

Let’s move forward with delete all the branches in GIT which are merged with master.

Git Delete Merged Branches

Deleting a pushing a single branch (merged or unmerged) can be simple. But deleting multiple branches which have acumulated over a period time and already merged can be tricky.

Here’s a one-liner which can help clean this up for us.

$ git checkout master && git branch -r --merged | grep -v master | sed -e 's/origin\//:/' | xargs git push origin

The above command, will remove the merged branches from remote or origin.

To perform similar clean up on local use the following one-liner:

$ git checkout master && git branch --merged | grep -v master | xargs git branch -d

That should do the trick as well.

There however, other options available to take care of the clean up on the remote using git-sweep. But the above one-liner performs pretty much the same thing.

Importantly, don’t forget to prune the branch from remote tracking!!

Git Delete Merged Branches

No Comments

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.