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! šŸ§‘ā€šŸ’»āœØ

ncutixavierSource