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! đ§âđ»âš