This guide covers how to delete branches in GitHub, what happens when they are deleted, and whether they can be recovered.
How to delete a branch in GitHub
Deleting a branch in GitHub can be done either locally via your Git command line or directly through the GitHub web UI. Each method suits different scenarios, such as cleaning up after a merge or removing unnecessary or outdated branches.
Deleting a branch locally
To delete a branch locally and then remove it from your GitHub repository, follow these steps:
- Ensure you are not on the branch you want to delete: Switch to a different branch, typically the main branch:Terminalgit checkout main
- Delete the branch locally: Use the
git branch -d <branch-name>
command for a safe deletion that checks for unmerged changes, orgit branch -D <branch-name>
to force the deletion:Terminalgit branch -d feature-branch - Push the deletion to GitHub: To remove the branch from your remote GitHub repository, use:Terminalgit push origin --delete feature-branch
Deleting a branch on GitHub
You can also delete branches directly on GitHub’s website:
- Navigate to your repository on GitHub.
- Go to the Branches tab
- Find the branch you want to delete and click on the trash bin icon next to it.
What happens when a branch is deleted?
When you delete a branch:
- Locally: The reference to that branch is removed from your local repository. The commits associated with the branch remain in your repository until they are pruned or garbage collected.
- On GitHub: The reference is removed from the repository, and the branch no longer appears in the list of branches. However, the commits themselves remain accessible via their hashes if they are not part of other deleted histories.
Can deleted branches be recovered?
Yes, deleted branches can often be recovered if necessary, as long as the commits were not explicitly purged from the repository.
Recovering a deleted branch
If you remember the commit hash that was the tip of your deleted branch, you can recover it:
- Find the last commit of the deleted branch: If you don’t remember the commit hash, you can find it using:This command shows a log of where your HEAD and branch pointers have been recently, including at the time you deleted the branch.Terminalgit reflog
- Create a new branch from the old commit: Once you have the commit hash, create a new branch pointing to it:Terminalgit checkout -b new-branch-name <commit-hash>
Deleting branches in GitHub helps keep your repository clean and manageable, especially after features have been merged or ideas abandoned. Although deleting a branch removes its reference, the commits generally remain accessible, allowing for recovery if necessary. This flexibility ensures that you can manage your project effectively without losing important work.
For further reading see the official GitHub documentation.