Git Excited
"Nobody knows git"

How to Recover Work You Didn't Commit

Have you ever been working on an unstaged file and then accidentally deleted or checked it out via git checkout so that all of your changes were gone? Have no fear, though on the surface it seems like an impossible situation to recover from, it’s actually relatively easy to retrieve your work again.

Git’s reflog records all changes that occur throught your repo, regardless of whether or not you actually committed any work. This log makes it easy to recover work that you’ve lost with an accidental checkout or deletion provided that you recently ran a command in git that would change where the HEAD was pointing to on your branch, like a checkout, commit, merge, or rebase might.

To recover a lost file:

  1. git reflog
    # b7fabd0 HEAD@{7}: checkout: update git ignore
    # a330391 HEAD@{8}: commit: test 3
    # 56cf779 HEAD@{9}: commit (amend): test 2
    # 602a89e HEAD@{10}: commit (initial): test 1
    

    Let’s say that after b7fabd0 you realize that you accidentally checked out important changes to a file. To recover those changes, simply checkout the hash prior to where you messed up. In our case, that would be a330391.

  2. git checkout a330391. And now your work is back! 😪