33.6 Git Branch Cleanup


Essentially, to remove locally all branches that have been merged into the current branch and so cleanup all the branching information, without losing any work since it’s already included in the current branch, we might do the following:

git branch --merged |
    egrep -v " (dev|main|`git branch --show-current`)$" |
    xargs git branch --delete

In detail, we might first go to the main or dev branch for your project, though this process will work for any branch. Suppose we operate from the dev branch.

git checkout dev
git pull

Then, to list all branches that have been merged into this current branch we run:

git branch --merged

We should see the dev (or current) branch is flagged:

* dev

We remove dev and main from the list, and in case the current branch is not one of them, we also remove the current branch from the list:

git branch --merged | egrep -v " (dev|main|`git branch --show-current`)$"

For all of the branches now remaining, since they have been merged into the current branch, we delete each of them:

git branch --merged |
    egrep -v " (dev|main|`git branch --show-current`)$" |
    xargs git branch --delete

Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0