Zum Inhalt springen

How to Restore a Deleted Local Git Branch or Commit (That Wasn’t Pushed)

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

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert