Skip to content

Instantly share code, notes, and snippets.

@DMeechan
Last active September 1, 2023 19:14
Show Gist options
  • Save DMeechan/db6932d2d65a37245caf8556f849d8f0 to your computer and use it in GitHub Desktop.
Save DMeechan/db6932d2d65a37245caf8556f849d8f0 to your computer and use it in GitHub Desktop.
How to clean up your Git branches

Clean up local branches 🏚

Prune merged branches

Delete all local branches which are merged to master (or whatever branch you choose to checkout)

git checkout master
git branch --merged | egrep -v "(^\*|master|dev)" | xargs git branch -d

Manually remove any old branches

Check which local branches are left and delete some of them manually:

git branch
git branch -D <names of the branches you want to delete>

# Example:
# git branch -D my-old-unmerged-branch-1 some-old-unmerged-branch-2 another-old-unmerged-branch-3

Clean up remote branches 🏘

Clear out any old local branches by syncing with the remote repository

By default, Git keeps hold of tracking branches, even if they no longer exist in their corresponding remotes.

Let's tell Git to clear them out if they don't exist in the remote using the -p flag:

git fetch -p origin

If you have any other remotes besides origin, make sure to run this command for those too!

Check which branches you want to delete

Before doing any changes, let's have a look at what merged branches we can prune from origin/master.

This won't delete anything, it just prints out which branches the command would delete:

git branch -r --merged | grep -v master | grep origin | sed 's/origin\//:/' | xargs -n 1 echo

Delete all merged branches on remote origin/master

If you're happy with those changes, let's delete all those branches from remote origin:

Note: if you have multiple remotes, you might need to add | grep origin after grep -v master to prevent it from pushing branches of other remotes to origin

git branch -r --merged | grep -v master | sed 's/origin\///' | xargs -n 1 git push --delete origin

The command above goes through each remote branch and deletes them sequentially, so it might take a while if you have hundreds of branches πŸ€·β€β™‚οΈ

Acknowledgments πŸ™πŸ»

Source: Stackoverflow - using answers from Adam Dymitruk, kuboon and L0LN1NJ4 and Alex Arriaga

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment