It’s Autumn here in the UK, and the leaves are falling from the trees leaving some empty branches. A similar principle happens when using Git and merging/deleting branches, leaving unused branches locally.
I recently ran into this issue whilst working on a Django project (code on my GitHub), creating branches whilst working, merging them and then ending up with local branches that are no longer needed, and references to remote branches that no longer exist.
The above image shows:
- my main branch (where other Git branches merge into),
- my local branches (which don’t exist in the remote repository anymore),
- my previous remote branches (prefixed with remotes/)
To remove local Git branches that are no longer required the following commands can be used:
Git Command | Description |
git branch | lists all local Git branches |
git branch -a | lists all Git branches (including remote branches) |
git branch -r | lists all remote Git branches |
git branch -d BRANCHNAME | deletes the local Git branch with the name BRANCHNAME. If the branch has not been merged then the command will give an error |
git branch -D BRANCHNAME | deletes the local Git branch with name BRANCHNAME. The capital D forces the deletion, unlike the version above with the lowercase d |
That takes care of local branches that are no longer required, but what about those “remote” branches that no longer exist? Well they are tracking branches and can be deleted using the follow Git commands:
Git Command | Description |
git remote prune origin | deletes the branches with remote/origin/ in their names |
git remote prune origin –dry-run | The –dry-run doesn’t do the deletion but does indicate what would be deleted |