Can you undo a commit in Git? There are many instances in which you may want to reset your current working directory to a former state, marked by a commit, tag, or other “treeish.”
The “reset” command can be destructive and wipe out your work. Be very careful when using this command.
Git is incredibly reliable with regard to saving the history of your project. Git uses several different kinds of references you can always return to. These types of revisions, references, and markers are often referred to as a “tree-ish,” including but not limited to:
- Commit (sha1) hash
And these various references can be combined and searched in different ways. For the purposes of this article we will be focusing on the most basic: commits and tags.
Every time you commit your code to repository, that commit is marked with a sha1 hash, for example:
3DA541559918A808C2402BBA5012F6C60B27661C. You can use the reset command to take your project back to a commit using this hash. Obviously, this hash is difficult to remember, so you only need to provide at least 5 digits. Or, you could refer to a tag instead.
Completely Undo a Commit
In this use case, presume that you have made changes to your project files, and performed a
commit, but you discover that you did not want to commit those changes, or you basically want to “rewind” to the state your project was in before you made and committed to these changes. The Git
reset command can easily allow for this:
git reset --hard
The command used in this context reverts automatically to the previous commit.
Alternatively, you can name a commit or tag to reset to, from any point in the project history.
git reset --hard <all or part of a commit hash, or complete tag>
Undo a Pull
If you have pulled changes into your project from a remote repository, but you have decided that you do not want to merge those changes yet, you can easily use the
reset command (as above) to reset back to the condition you were at before pulling:
git reset --hard
Using tags is another way to mark a state of your project to which you might want to restore. For example, if you have a tag called “V1.3”, you can use that tag in the command:
git reset --hard V1.3
That’s how you can undo or restore a commit in Git using the
reset command. Be sure to check some of the other Git resources in the support center:
Let our Managed Hosting team configure your servers while you work on building your brand!