Git Tutorial 29 – How To Undo Local Last Commit Using Git Reset
As a part of GIT Tutorials End To End, we will learn to undo the local last commit using the git reset command.
I will expect that you are aware of the basic concepts and commands of GIT. But if you are a beginner in GIT then I strongly recommend you to refer GIT Basic Commands and Concepts section on my blog first.
Did you know that I have started a YouTube channel as well and I need your support to make it successful. Please do watch content then comment, like, share, and obviously subscribe.
Undo local last commit
We add, commit and push created and modified files to a remote git repository. During the development, we may create multiple commits. For some reason, you may need to undo these commits. In this post, we will learn to undo the last local commit. We can undo any number of last commits in a similar pattern.
To explain with an example, I am creating some commits below and will not push to remote.
Creating the first commit with an empty file named “filea.txt”.
Creating the second commit by adding a line in “filea.txt”.
Creating the third commit by adding another line in “filea.txt”.
So we have three commits and HEAD is pointing to the latest commit.
Now I need to undo the last commit i.e. 34b2cfa. “Undo the last commit” is not straightforward and may confuse you with output. You have the below options to use with the git reset command –
- You just want to remove the commit entry from the commit log and do not want to delete any changes done as part of the commit. We need to use the “–mixed” option. It is the default option as well.
- You want to remove the commit entry from the commit log and want to delete any changes done as part of the commit. We need to use the “–hard” option.
Command to reset commit is below –
git reset <howDoYouWantToReset> HEAD~<N>
We need to pass howDoYouWantToReset as explained above. HEAD~1 will reset or undo the last commit while HEAD~2 will undo the two last commits.
git reset with –mixed option
The default i.e. mixed option removed the commit entry from the commit log as shown above. Now HEAD is pointing to the second commit we made. It did not remove any changes made in filea.txt as part of that commit. It just undid the commit. You can see that filea.txt still contains both lines.
git reset with –hard option
If we want to remove all changes from files as well then we should use –hard option. If we undo the last commit now then filea.txt will move to d8783ab commit. At that time filea.txt was empty.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.