We’ve all been there. Whether it was due to a lack of caffeine or hunger pangs before lunch, a bug managed to sneak its way into the repository, and now it needs to be eradicated. Fortunately, git revert is the precise tool you need to excise that troublesome commit.

Let’s envision our repository history like this:

The “revert” command operates as follows: it effectively undoes the changes introduced by the specified commit by generating a new commit. Suppose you wish to revert the last commit made on your current branch:

$ git revert HEAD

Executing this command results in the creation of a new commit that reverses the changes introduced by the last commit. The repository will now appear as follows:

You can also revert any commit by specifying its SHA. However, if the commit you wish to revert doesn’t apply cleanly, you’ll need to manually resolve the merge conflicts.

By default, git revert opens your default text editor to allow you to modify the commit message for the revert. It’s advisable to provide an explanation for why the changes are being reverted. If you prefer not to edit the commit message, you can add the –no-edit option.

Another useful option is the -n or –no-commit flag, which retains the reverted changes in your working directory without automatically committing them. This can be helpful if you need to further edit files to complete the revert or if you intend to revert multiple commits.

Reverting merge commits can be a bit tricky. If you encounter the following error message when attempting to revert a merge commit:

fatal: Commit 137ea95 is a merge but no -m option was given.

You’ll need to specify which parent commit of the merge should be considered the mainline. This can be achieved using the -m or –mainline option followed by a number argument. For instance, to revert the changes introduced by the first parent commit of the merge, you would use:

$ git revert HEAD~1 -m 1

Similarly, using -m 2 would revert the changes introduced by the second parent commit. The default commit message will indicate which commit was reverted.

The Git documentation recommends referring to a message from Linus if you require assistance with resolving merges. If you have other insightful applications of the revert commit, share them with us!