Reverting a Commit

Once in a while, I'll make a commit that I wish I hadn't. In many cases, the reason isn't that I don't want the change at all, but rather that it's not quite ready.

It's pretty easy to revert something while keeping your work so that you can re-commit it later, by using a combination of branching and the git revert command.

(Optional) Save your work

First, I start by saving my work using the git branch command. Here' I'm creating a new branch called my_saved_work, which I'll use to save the work that I will be reverting.

If you don't want to save your work, you can just skip this step and continue with reverting your commit.

$ git branch -b my_saved_work
Switched to a new branch 'my_saved_work'

This branch is an exact copy of the repository as it stands now, before I begin reverting anything. Now that I have my work saved on its own branch, I'll switch back to the master branch again.

$ git checkout master
Switched to branch 'master'

Revert your commit

Now, I'll revert the erroneous commit using git revert:

$ git revert HEAD

[master e701a7a] Revert "Updated buildfile."
 1 file changed, 1 insertion(+), 1 deletion(-)

This adds a new commit to your history that reverts the old one. You can check it out using git log:

$ git log --oneline
e701a7a Revert "Updated buildfile."
d57f240 Updated buildfile.

Then, I push the new commit, which reverts the old one--it's a good thing I saved my work in a separate branch! This will make it easy to restore later...

$ git push

(Optional) Re-commit your changes

Since my changes have been stored on the my_saved_work branch, I can continue updating the stuff I was working on and make it perfect.

$ git checkout my_saved_work
Switched to branch 'my_saved_work'

... I do some work here, commit my changes, and so forth ...

Later, once I've fixed whatever issues caused me to want to revert my change and have committed them, I'll merge the my_saved_work branch back into the master branch (or whatever branch I'm working on).

$ git checkout master
Switched to branch 'master'

$ git merge my_saved_work
Merge made by the 'recursive' strategy. |    1 +  |    5 ++++-  |    1 +
 3 files changed, 6 insertions(+), 1 deletion(-)
 mode change 100644 => 100755
 mode change 100644 => 100755

This merges in the original change plus all the additional changes I've made on the my_saved_work branch.

Finally, I push the updated master master branch, and I'm finished!

$ git push