Accidentally deleted a local Git branch before pushing it? š± Donāt panic ā if the commits havenāt been garbage collected, you can still bring it back using Gitās powerful internal logs.
Hereās how to recover your branch step by step:
š Step 1: Check the Git Reflog
Git keeps a history of everything youāve done even deleted branches in something called the reflog.
Open your terminal and run:
git reflog
This will show a list of recent Git actions, including checkouts and commits. It might look like this:
a1b2c3d HEAD@{0}: checkout: moving from feature-x to main
d4e5f6g HEAD@{1}: commit: Add new login functionality
...
š Look for the last commit hash (e.g., d4e5f6g
) from the deleted branch.
š± Step 2: Recreate the Deleted Branch
Once youāve identified the right commit, you can bring the branch back with:
git checkout -b your-branch-name <commit-hash>
Example:
git checkout -b feature-x d4e5f6g
Boom š„ ā your branch is back!
š§¹ Bonus Tip: Don't Wait Too Long
Git eventually garbage collects old commits, so try to restore the branch as soon as possible to avoid permanent loss.
ā Summary
Action | Command |
---|---|
View Git reflog | git reflog |
Restore branch | git checkout -b branch-name <commit-hash> |
By keeping this trick in your Git toolbox, youāll never fear accidental branch deletions again. Happy coding! š§āš»āØ