How To Remove Old and Merged Git Branches Easily

Overview

Let's say that you do your all of your development on a feature branch in your local repository and push it to the remote repository creating a pull request. Then in your remote repository(say, GitHub), you merge the feature branch into main branch after review, then get rid of the feature branch.

However, you still have the feature branch in your local repository. If you keep doing this, you will have growing number of feature branches that are no longer needed locally. You need to clean them up and the below is how you do it.

Case I

Terminal
# Fetch the latest from the git
git fetch
# Check the list of local git branches
git branch
# Delete all local branches that have been merged to main branch and then deleted in the remote repository
git branch --verbose | grep ': gone]' | grep -v '\*' | awk '{ print $1; }' | xargs -r git branch -d
# Check the list of local git branches that remain
git branch

Case II

In case where you merged the feature branch into main branch, but haven't deleted it yet in the remote repository, you can use the following commands to remove the merged branches locally:

Terminal
# Fetch the latest from the git
git fetch
# Check the list of local git branches
git branch
# Delete all local branches that have been merged to main branch, but haven't yet deleted in the remote repository
git branch --merged main | grep -v '^\* main' | xargs -n 1 -r git branch -d
# Check the list of local git branches that remain
git branch
all posts

Comments

© 2022 Youngjae Jay Lim. All Rights Reserved, Built with Gatsby