Rewriting Git History | git reflog
The git reflog command
Git has a feature called the reflog that tracks updates to the tips of branches and HEAD. This lets you return to states that are no longer referenced by any branch or tag. Even after rewriting history, the reflog records previous states of the branch, so you can go back to them when needed.
Usage
git reflog
Displays the reflog for the local repository.
git reflog --relative-date
Displays the reflog using relative dates, such as “2 weeks ago”.
Additional notes
Every time the current HEAD is updated, such as when switching branches, rewriting history, or simply creating a new commit, a new entry is added to the reflog.
Example
Consider the following example to understand git reflog.
0a2e358 HEAD@{0}: reset: moving to HEAD~2
0254ea7 HEAD@{1}: checkout: moving from 2.2 to master
c10f740 HEAD@{2}: checkout: moving from master to 2.2
This reflog first shows a checkout from master to a branch named 2.2, then a checkout back to master. After that, a reset moves to an older commit. The reflog displays the newest entry at the top, labeled HEAD@{0}.
Even if the reset was unintended, the original commit that HEAD pointed to before the two commits were reset, 0254ea7, remains in the reflog.
git reset --hard 0254ea7
This lets you use git reset to return master to a commit that existed in the past. In this sense, the reflog acts as a safety net for rewriting history.
Remember that the reflog is only a safety net after changes have been committed to the local repository, and that it only records movements of HEAD.