Graham King

Solvitas perambulum

Cleaning up old git branches

software branch git
Summary
To clean up old Git branches, especially when using git-flow, start by switching to your main branch (e.g., `develop` or `master`). List all merged branches using `git branch -a --merged`. To identify outdated branches, use a script that shows the last commit date for each branch: ``` 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 ``` Check your ticket tracker to ensure corresponding tasks are closed. Delete local branches with `git branch -d <branch_name>` and remote branches with `git push origin :<branch_name>`. Ensure consistency across your team's setup by running `git remote prune origin`. Remember, deleting branches does not lose commits, just named references to them.

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.

Happy pruning!