info
This article is a translated version of the Dutch version that I wrote for my employer’s website some time ago. I translated it in to English and posted it here so it can reach a bigger audience and help more people!

Most developers nowadays use a program like git to manage different versions of their code, and to make working together with others easier. This is also known as a vcs, a version control system. Other options like svn or fossil exist, but git is the most popular.

git can also be rather intimidating for a beginner, and it’s easy to make mistakes that can result in loss of progress. You might already have encountered this xkcd comic about git:

XKCD 1597

source

You might also have encountered these losses in progress that I mentioned. Who hasn’t? We’ll take unintentionally deleting some commits as an example. Luckily, you can recover these with git reflog!

Where git log shows you the history of the commits in a repository, git reflog shows different kinds of changes. For example, when you switch to a different branch or commit, this gets recorded in git reflog:

commandline showing the output of git reflog

In this image you see the SHA1 hash and some info about the action (clone, switching branches, committing).

Let’s say that I accidentally lost my first commit (because of a bad rebase, a corrupt repo, etc…). I can now still recover it by checking out the SHA1 hash! We can simply do something like git checkout 41935ef to go to that commit again! Or we can do git checkout master && git reset --hard 41935ef to reattach the commit to the master branch!

As you can see, it’s pretty simple to recover lost changes!

warning
Be careful! The reflog gets cleaned up automatically after a while.You can’t recover these cleaned up changes anymore. So don’t depend on this functionality too often!

Did you enjoy this post? Buy Me a Coffee at https://ko-fi.com/stenbrinke.nl