DEV Community

Akash Kumar
Akash Kumar

Posted on

Git Gone Wrong: How I Lost My Code and Found My Sanity (Sort Of)

Just lost all my code today! 😱 After a long day of coding, I pushed my changes to Git—did the usual git add, git commit, and then git push. Everything seemed fine, so I switched back to my working branch, thinking the post was safely committed. But then I saw it... the nightmare—no recent commit. 😨

I was like, "What the heck just happened?" My code was gone! I checked my terminal (I use Linux, by the way), and saw that my local changes had been merged with the GitHub code. Everything was lost.

After some frantic Googling and reading through Git docs, I learned that if you’ve switched branches recently, Git still keeps the previous state saved. Phew!

I ran git show ORIG_HEAD, and luckily, I found the lost state. Then, I created a branch from that commit:

git branch recovered-work ORIG_HEAD
git checkout recovered-work
Enter fullscreen mode Exit fullscreen mode

Next, I discovered git fsck, which can help find dangling commits. There it was, a dangling commit with all my changes. I verified it with:

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

Finally, I created a branch from that commit:

git branch recovered-work <commit-hash>
Enter fullscreen mode Exit fullscreen mode

And merged it back into main. Crisis averted!

Lesson learned: Always double-check your branches before committing. Git is powerful, and recovery is possible when things go wrong. 💡

Hope this helps you all, and one thing: Don’t be dumb like me! Be careful with merging, pulling, and pushing to GitHub. 😅

Top comments (0)