Committing changes is a regular phenomenon when you work with Git. The traditional workflow of Git is such that you build your project in modules or pieces, add them up to the staging area, and commit them in the working tree. After committing, your code becomes ready to push on the remote repository.
However, if you have ever been in a situation where after committing changes or files, you realize that you just made a mistake that you don’t want to push, or you have forgotten to add a file, then this guide is for you to walk through the mechanism of uncommitting changes in Git.
Following are the possible commands that you can use to uncommit Git changes according to your situation.
Table of Contents
Case#01: Undo Last Commit and Keep Previous Changes
If you want to undo your last commit while leaving the previously committed changes unstaged, then use the command mentioned below:
$ git reset HEAD^
Case#02: When you Want to Keep the Uncommitting Data in the Staging Area
If you want to undo your last commit while keeping all other changes staged or intact (i.e., the data being uncommitted will not be lost), then use the command mentioned below:
$ git reset --soft HEAD^
Case#03: When you Want to Uncommit both the Committed Data and the Data in the Staging Area
If you want to undo not only the committed changes but also the uncommitted but staged changes (i.e., everything new will be lost, and you will get back to the previously committed history), then use the command mentioned below:
$ git reset --hard HEAD^
Case#04: If you Want to Go Back by Two Commits
If you want to go back by two commits, then use the command mentioned below:
$ git reset HEAD~2
You can use the –hard and –soft options according to your situation and can also change the number of commits to go back by using the above command.
Case#05: When you Want to Undo a Specific Commit
If you want to undo a specific commit, then you have to put the unique hash number of that commit in the command from history. Here again, you can use the –hard and –soft options by choice, then use the command mentioned below:
$ git reset [commit_hash]
If you are a Windows user, keep the hash commit number or HEAD within double-quotes. For example:
$ git reset “HEAD^”
$ git reset “f145h7r”
Conclusion
It is a common mistake by developers to commit something mistakenly and realizing it later. Fortunately, Git provides you with enough command to revert from the mistaken state according to your situation and needs. In this brief article, we discussed various scenarios of undoing a commit. We hope you can find help from this guide to resolve your issue as well.