I would easily describe git as one of the most important pieces of software out there. It enables collaboration, version control and has tons of features that thousands of developers use on a daily basis.

Git is powerful, but with great power comes great responsibility, git is complex too, when you mess up it can get very frustrating and difficult to recover.

To help us, the authors of git created a logging mechanism called git-reflog which keeps track of every action you perform that moves the tip of the HEAD(commit, reset, amend etc).

A typical scenario is when you accidentally amended a commit instead of making a separate one, how do you "un-amend"?

I could just do a soft reset and make two separate commits, but this has its drawbacks. What if the previous commit was not yours? There is a better way, use reflog!

I amended my last commit a change that should have been in a separate commit and since I amended, git log displays a single commit:

achilles:[main]~/myapp$ git log --oneline
490b784 (HEAD -> main) Add a title to the page
c7a8176 Add a button to the homepage
dc5765f Initial commit

To see the change I can use git reflog:

achilles:[main]~/myapp$ git reflog
490b784 (HEAD -> main) HEAD@{0}: commit (amend): Add a title to the page
55200f5 HEAD@{1}: commit: Add a title to the page
c7a8176 HEAD@{2}: commit: Add a button to the homepage
dc5765f HEAD@{3}: commit (initial): Initial commit

I can clearly see the change, soft reset it with git reset --soft HEAD@{1} which is the point where I still have not amended my change and now I can make another commit with the previous changes.

In some cases, you might want to completely discard the changes and restore the working directory: git reset --hard HEAD@{1}

Notice the HEAD@{1} notation I am using to reset which indicates the 1st listing in the reflog record.

The same practice can be applied if you hard reset or remove something by accident, again you reflog to see at what point you made the mistake and carry out accordingly.

Although git is a distributed system, it is worth mentioning that reflog is kept only locally and cannot be pushed or fetched.

A lot of people describe reflog as a safety net and I couldn't agree more. It definitely saves me from a lot of hassle.

References:

https://git-scm.com/docs/git-reflog https://stackoverflow.com/questions/1459150/how-to-undo-git-commit-amend-done-instead-of-git-commit https://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html