How to redo the last commit removed with hard reset?
git reflog
git reset --hard HEAD@{1}
To redo a commit removed with hard reset, first find its reference with git reflog
. Once you have the reference, restore it with git reset --hard REF
.
In the example below we have a repository with 3 commits. The first commit adds articles_controller
. The second commit adds the articles_controller.new
method and the third commit adds the articles_controller.index
method. Git log shows these commits in reversed chronological order.
The last commit is then removed with git reset --hard HEAD~1
.
If it turns out that the removed commit is still needed, we can find it's reference with git reflog
. In our case the commit is referenced with da3c693 HEAD@{1}: commit: Add articles_controller.index
.
The commit is redone with git reset
referencing it in git reset --hard HEAD@{1}
.
git log --oneline
da3c693 (HEAD -> main) Add articles_controller.index
d09a1a6 Add articles_controller.new
509b108 Add articles_controller
git reset --hard HEAD~1
HEAD is now at d09a1a6 Add articles_controller.new
git reflog
d09a1a6 (HEAD -> main) HEAD@{0}: reset: moving to HEAD~1
da3c693 HEAD@{1}: commit: Add articles_controller.index
d09a1a6 (HEAD -> main) HEAD@{2}: commit: Add articles_controller.new
509b108 HEAD@{3}: commit: Add articles_controller
git reset --hard HEAD@{1}
HEAD is now at da3c693 Add articles_controller.index
See git reflog and git reset to learn more about them.