Git | How to recover your lost work

I recently helped a colleague with this issue and I thought that it was a good tip to share because I realized that most developers don’t know that they can recover their work even after a reset –HARD or things like that.

That’s actually what I love so much with Git. If you make a mistake, you can always go back and fix it. That would be nice to have this option in real life ;)

So, I’m gonna screw my project and show you how to get back my work.

Here is my last work: transaction.cpp an entire file with many lines of code.

“log before reset”

“work before reset”

First, let me reset –HARD my work by executing this command:

$ git reset --hard 179d0feb547c43970d195204bb124b620918c48c

I precise the commit -1 hash

> HEAD is now at 179d0fe Merge branch 'thomas/branch-test-2' into develop

Nooooooooo what did I do that ?!! I have no backup :( I can’t find my file anymore!

$ cat transaction.cpp

> cat: transaction.cpp: No such file or directory

Nooooooooooooooooooooo !

Hahaha, no don’t worry I’m kidding! I can easily get it back 8-) Let’s go!

$ git reflog

Display the “operations” history

1
2
3
4
5
179d0fe HEAD@{0}: reset: moving to 179d0feb547c43970d195204bb124b620918c48c
a2417f8 HEAD@{1}: commit: feat(transaction): build everything
179d0fe HEAD@{2}: checkout: moving from develop to thomas/demo-recover
179d0fe HEAD@{3}: checkout: moving from thomas/demo-recover to develop
179d0fe HEAD@{4}: checkout: moving from develop to thomas/demo-recover

I want to go back to my commit feat(transaction): build everything, so I’ll use HEAD@{1}

$ git reset --hard HEAD@{1}

> HEAD is now at a2417f8 feat(transaction): build everything

That’s it! I recovered my file, here is the proof:

$ cat transaction.cpp

1
2
3
4
5
6
7
8
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <consensus/validation.h>
#include <net.h>
...
Built with Hugo
Theme Stack designed by Jimmy