DEV Community

Documendous
Documendous

Posted on

1

How to Get Back a Lost Git Branch

Losing a feature branch in Git can be frustrating, but there’s usually a way to recover it. Whether it was deleted, force-pushed, or just seems to have disappeared, here’s how to bring it back.


1. Check Git Reflog

Git keeps track of changes to your branches with git reflog. This can help find lost commits:

 git reflog
Enter fullscreen mode Exit fullscreen mode

Look through the list to find the commit hash where your work was last intact.

Once you’ve found the right commit, you can restore it.


2. Restore Your Work

Option 1: Create a new branch from the lost commit

Use the commit hash from reflog to make a new branch:

 git checkout -b recovery-branch <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Now your work is back in a safe place.

Option 2: Reset your branch

If your feature branch still exists but is missing changes, you can reset it:

 git reset --hard <commit-hash>
Enter fullscreen mode Exit fullscreen mode

Be careful: This will erase any changes since that commit.


3. Check the Remote Repository

If the branch was changed or deleted on the remote, check for lost commits:

 git fsck --lost-found
Enter fullscreen mode Exit fullscreen mode

If this shows lost commits, you can inspect them:

 git show <commit-hash>
Enter fullscreen mode Exit fullscreen mode

If the branch was force-pushed, you might still find its history:

 git reflog origin/feature-branch
Enter fullscreen mode Exit fullscreen mode

4. Merge or Push Your Changes Back

Once you’ve recovered your work, you can merge it back:

 git checkout feature-branch
 git merge recovery-branch
Enter fullscreen mode Exit fullscreen mode

Or, if the branch was deleted:

 git branch feature-branch recovery-branch
 git checkout feature-branch
Enter fullscreen mode Exit fullscreen mode

Then push it:

 git push origin feature-branch
Enter fullscreen mode Exit fullscreen mode

Conclusion

Git keeps track of more than you might think, so there’s usually a way to recover lost work. The key is to act quickly and check reflog before assuming your work is gone.

Have you ever lost a branch and brought it back? Let me know how you did it!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay