September 16, 2011
After a while working with git, you end up with lots of branches, especially if you use git-flow inspired feature branches. Here’s one way to clean them up.
For any branch, I want to know whether it has been merged, when the last commit was, and ideally if the matching ticket in our tracker has been closed.
Switch to your main branch, usually develop or master:
git checkout develop
List all the branches which have been fully merged into it:
git branch -a --merged
Show last commit date for a branch:
git log -1 --pretty=format:"%Cgreen%ci %Cred%cr%Creset" <branch_name>
Putting all that together, for all branches, gives us (thanks brunost and unixmonkey7740):
for k in $(git branch -a --merged|grep -v "\->"|sed s/^..//);do echo -e $(git log -1 --pretty=format:"%Cgreen%ci %Cred%cr%Creset" "$k")\\t"$k";done|sort|more
Most of my branches are named
features/<ticket-id>, so I bring up the above list in one window, and the ticket tracker in a browser, and work through them.
To delete a branch:
# If you have it checked out locally git branch -d <branch_name> # Delete remote branch git push origin :<branch_name>
To keep you safe from typos,
git branch -d will refuse to delete branches that haven’t been merged.
Finally, once you have deleted all the old branches, your colleagues will need to bring their remote names in sync:
git remote prune origin
Remember that in git branches are just like symlinks, so you’re not losing any commits by deleting a branch, you’re just losing a named reference to a commit.