Keep Calm and Use Git Reflog
Git is a very powerful tool but it takes a fair amount of time to masterize it. It can be particuarly easy to break or lose things when you amend some commits, resolve conflicts or force push your changes.
In this blog post, I will show you how to use the
git reflog command to retrieve commits that you thought you lost forever.
Retrieve an amended commit
The first use case I will show is when you amend a commit:
1 2 3 4 5
If you think that the first commit is lost, read on.
git reflog command allows you to display all git commands that you performed on your repo and, most importantly, the associated commit hash. In fact, these commits are not lost, they are just not in the tree anymore but you can still check them out, cherry-pick them or do whatever you need to do.
1 2 3 4 5 6 7 8 9 10 11
Recover an erroneous merge
The second scenario is when you rebase a branch on an other one and you have conflicts.
1 2 3 4 5 6 7 8 9
This is the resulting tree (note that the hello.txt has been modified on the two branches and there is a conflict):
1 2 3 4
reflog looks like this:
1 2 3 4 5 6 7 8 9
Now we rebase
master and we resolve the conflicts.
The thing is that we made a mistake and took the wrong version of
hello.txt. Since we did a rebase, we rewrote the history and we could think we lost the “good” version of
In fact, the
reflog will display a line for each commit you rebased so it is very easy to pick the one where you made a mistake.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
If you want to go back and fix it, you just have to check the commit out, delete the current
develop branch (since it is not in the correct state) and create a new
develop branch based upon the right commit.
1 2 3
I think you got the idea, Git keeps everything that you committed. Thus, don’t panic if you find yourself in a situation where you erase a previous commit and think about the
git reflog command to dive into your history and look for the information you thought you lost!
Crafties réalise des audits de code, des formations, des accompagnements et des développements. Vous pouvez nous contacter à email@example.com pour tout besoin.