git is an advanced tool. It features a philosophy that is dear to my heart: to treat developers as smart and responsible folks. This means that a lot of power is at your fingertips. The power to also shoot yourself in the foot – arguably with a titanium vest on – but shoot yourself nonetheless. The topic of this post is to confirm what my colleague Charles O’Farrell said very well in the ever popular “Why Git?” article some time ago: [...] Git is actually the safest of all the DVCS options. As we saw above, Git never actually lets you change anything, it just creates new objects. [...] Git actually keeps track of every change you make, storing them in the reflog. Because every commit is unique and immutable, all the reflog has to do is store a reference to them. This means you’re safe from harm and your code is always preserved, but there are situations where you might need some conjuring to get it back. Let me give you a few real world examples of how to recover from trouble, going from simple to advanced: Table Of Contents How To Undo A (Soft) Reset And Recover A Deleted File If You Lose A Commit During An Interactive Rebase How To Undo reset –hard If You Only Staged Your Changes How To Undo A (Soft) Reset And Recover A Deleted File If you delete a file with git rm and immediately after you git reset your working directory (which is called a soft reset), you will find yourself with a missing file and a dirty working directory like the following: 1234567# On branch master # Changes not staged for commit: # (use "git add/rm file..." to update what will be committed) # (use "git checkout -- file..." to discard changes in working directory) # # deleted: test.txt # There are a couple of simple ways to go about restoring the file. One is to use a git reset –hard which will recreate the missing files but it will delete any local modifications you might have in your working directory. The second is to just re-check out the file yourself with git checkout test.txt. In a slightly different scenario, if the file was removed in an earlier commit, you can recover it by noting down the exact commit where the file was deleted and use the reference to pick the commit immediately before: 1git checkout commit_id~ -- test.txt Where the ~ (tilde) sign means the one before this one. If You Lose A Commit During An Interactive Rebase Interactive rebase is one of the most useful tools in the git arsenal; It allows to edit, squash and delete commits interactively. Personally I love to clean and streamline commits before sharing them with others. It’s nice when each commit is an understandable and logical chunk of work. In the heat of development, or in a local private branch, I might commit furiously for a bit, then [...]