How I Messed Up My Git Commits and Fixed Them Like a Pro

Development

How I Fixed My Git Mishap (and You Can Too)

Let me tell you a funny (but stressful) story about how I managed to mess up my Git history and then fixed it like a pro.


The Problem: A Commit I Didn’t Want

It started with a simple task. I had a list of commits, and one of them was just plain wrong. It had no business being in my project, so I decided to delete it.

Step 1: I opened the commit history
To check the commits, I ran:

git log --oneline

It showed me something like this:

c3f2e7b - Added cool feature  
b8d6a4c - Fixed an issue
a1d2f3g - This one is bad (delete me!)

I found the bad commit (a1d2f3g) and confidently went ahead to delete it.


The First Mistake: Deleting the Wrong Commit

I followed the steps to delete the commit:

  1. Ran:
    git rebase -i HEAD~3
  2. In the editor, I accidentally marked the wrong commit as drop:
    pick b8d6a4c Fixed an issue
    drop c3f2e7b Added cool feature
    pick a1d2f3g This one is bad (delete me!)
  3. I saved and closed the editor.

But wait… instead of deleting the bad commit, I deleted a good one! 😱


Fixing the Mess: Restoring the Deleted Commit

Thankfully, Git is forgiving. Here’s how I restored the commit I accidentally deleted:

  1. I ran:
    git reflog
    This showed me a history of all my actions, even the mistakes:
    abc1234 HEAD@{0}: rebase -i (finish): returning to HEAD~3
    def5678 HEAD@{1}: commit: Added cool feature

    I spotted the hash of the deleted commit (def5678).
  2. I brought it back using:
    git cherry-pick def5678
    This reapplied the deleted commit to my branch.

Deleting the Right Commit This Time

Now that I had everything back in place, I returned to my original mission: deleting the bad commit.

  1. I ran git rebase -i HEAD~3 again.
  2. This time, I marked the correct commit as drop:
    pick b8d6a4c Fixed an issue
    pick c3f2e7b Added cool feature
    drop a1d2f3g This one is bad (delete me!)
  3. I saved, and the bad commit was finally gone.

Git Makes Mistakes Fixable

I learned two important lessons:

  1. Always double-check before deleting anything in Git.
  2. Even if you mess up, Git has tools like reflog and cherry-pick to fix it.

Next time you’re in a similar situation, remember: Git’s got your back, as long as you know which commands to use. 😊

Leave a Comment