Recover a lost or deleted git commit

Alex Weidmann
GitMonitor
Published in
2 min readJul 11, 2016

--

Have you ever had a lost commit? Perhaps you did a git reset and then realized you actually lost something important? Maybe you deleted an entire branch thinking all the work was done and merged, only to discover a commit missing in master. Luckily, you can usually go back through your git reflog and scan through it until you find the commit you’re looking for.

The Reflog

The reflog command in git is very powerful. Anytime the tip of one of your branches is updated, a new reflog entry is saved. This makes is extremely useful to look at how code or files existed in the past, on any branch in your repository. Here’s what a reflog might look like:

For example, you can use git reflog HEAD@{4} which will show you where HEAD was 4 steps ago (or 4 commits ago). You can also recover an entire branch from a previous date. If something catastrophic happened and you knew the codebase was good last week, you could find that good commit using git reflog master@{three.days.ago}.

You can also just parse the reflog line by line to see every commit/change to every branch in your repository until you find that commit you’re looking for.

$ git reflog
d2f35f1 HEAD@{5}: checkout: moving from master to develop
d2f35f1 HEAD@{6}: pull: Fast-forward
2f01b11 HEAD@{7}: checkout: moving from develop to master
8564ea1 HEAD@{8}: rebase finished: returning to refs/heads/develop
8564ea1 HEAD@{9}: rebase: develop
2f01b11 HEAD@{10}: rebase: checkout master
1ff3481 HEAD@{11}: checkout: moving from master to develop
2f01b11 HEAD@{12}: commit: this was a commit message

Recover that lost commit

In your repository, run git reflog (If you know what branch the commit was in, use git reflog <branch>)

Look for the commit message that went missing

Find the associated SHA, and run git show <sha>

View your missing code in all its glory

Use git cherry-pick <sha> to get that lost commit into a new branch

GitMonitor.com

Instant email, Slack message & push notification when:

  • Any of your protected branches are force pushed to
  • Any commits are made directly to protected branches
  • A new team member of collaborator is added to the repository
  • A pull request is merged with no comments
  • A pull request is merged without an “LGTM” comment
  • A pull request is merged by an unauthorized user
  • A protected file is modified or deleted in any branch

--

--

co-founder @GitMonitorApp, a developer playing golf and writing #ruby, #elixir and #javascript