Restoring a Deleted Branch
1. Find the Branch’s Last Commit
When a branch is deleted, the commits are not lost. They remain in the repository’s history. You can find the commit where the branch was pointing before it was deleted using the reflog.
Steps: View the Reflog:
The reflog records updates to the tip of branches and other references.
git reflog
This command will display a list of recent commits. Look for the commit where the branch was last updated.
Identify the Commit Hash:
Identify the hash (SHA-1) of the commit that the deleted branch pointed to. For example:
c4f5a2d HEAD@{2}: commit: Fixed issue #123
Restore the Branch:
Once you have the commit hash, you can recreate the branch.
git checkout -b <branch-name> <commit-hash>
For example, to restore a branch named feature:
git checkout -b feature c4f5a2d
How to Change a Git Commit Message After a Push?
Accidentally deleting a branch or commit in Git can seem alarming, but Git’s powerful version control capabilities often allow you to restore them with relative ease. This guide will walk you through the steps to recover a deleted branch or commit.
Table of Content
- Restoring a Deleted Branch
- Using GitHub or GitLab
- Restoring a Deleted Commit
- Using git cherry-pick
- Conclusion