This guide will explain how you can undo a commit in git.
Git Revert Last Commit (preserve changes)
To undo a previous commit in git, we use the git reset command. In addition, we can use the HEAD, which is a pointer to your last commit in a target branch.
To undo the last commit while preserving the changes made to the files, use the git reset with the –soft parameter.
An example is as shown:
The command above moves the branch to the previous commit. You can verify that the undo is successful by running the command:
Git Revert Last commit (Discard Changes)
In some cases, you may want to revert your last commit and discard all the changes made to the repository.
You can use the git reset command with the –hard parameter.
An example is as shown:
The command above should undo your last commit and discard all the changes made.
Note that the command above is irreversible. Use with caution.
Git Revert to Specific Commit
Suppose you want to revert to a commit that is way behind. You could manually determine the number of commits that come before it and run:
However, the method above is not applicable. Instead, you must determine the number of commits and then revert to it.
You can solve this by using a commit hash. A commit hash is a cryptographically unique identifier which identifies a specific commit in a given repository.
To view the history of your commits, use the command:
The command should return the history of the commits, including the author, date, and the commit message.
An example output is as shown:
Author: artemis37 <57583117+Captainsalem@users.noreply.github.com>
Date: Fri May 13 00:42:28 2022 +0300
Add source code and fixes.
Note the commit hash.
For simplicity, you can fetch the commit hash and message using the command:
This should return output as:
The above command returns a summary of the commits.
You can use this hash to revert to a specific commit.
An example is as shown:
The command above should revert to the commit with the specified hash.
Git Amend Last Commit
If you only want to edit the last commit instead of reverting, you can use the git commit –amend flag.
For example, to amend the last commit message, we can do the following:
Conclusion
With that, you have a way to undo your commit to a specific commit. Use the git reset commit with caution as it is irreversible.