Reverting commits with Git without losing history

Today at work, I decided to roll back the previous few commits I had made, but I didn’t want to git reset --hard and throw away history or mess up anyone else who might have pulled from my branch, so I decided to git revert, but I wasn’t quite sure the syntax.

I pulled out my normally reliable name-brand search engine and, after an unusually long search, found the “answer.” But it wasn’t quite right. It failed to revert one of the commits I wanted to revert. So I’m putting the answer here in hopes it saves someone else some pain.

I make three commits below and then revert the last two…

mkdir test_git_revert
cd test_git_revert/
git init .
vim a.txt
git add a.txt
git commit -m "create a.txt"
vim b.txt
git add b.txt
git commit -m "create b.txt"
vim c.txt
git add c.txt
git commit -m "create c.txt"
git log

  commit b59b5ecddc5284358da38635dc0829f629be11a7

  Author: James Lavin <james@fakedomain.com>

  Date:   Thu Mar 13 16:58:42 2014 -0400

      create c.txt

  commit 31fec743e007f94eb4738d1108c79b38dfa6cff0

  Author: James Lavin <james@fakedomain.com>

  Date:   Thu Mar 13 16:58:19 2014 -0400

      create b.txt

  commit a9d88ae06cedf5296297705142020a5264c839b8

  Author: James Lavin <james@fakedomain.com>

  Date:   Thu Mar 13 16:57:56 2014 -0400

      create a.txt

To revert the previous two commits and keep the first, I ran the following:

git revert --no-edit a9d88ae06cedf..b59b5ecddc5284

which is equivalent to:

git revert --no-edit <last_good_commit_SHA>..<last_bad_commit_SHA>

The output:

[master 4323ac0] Revert "create c.txt"

 1 file changed, 1 deletion(-)

 delete mode 100644 c.txt

[master c49aa86] Revert "create b.txt"

 1 file changed, 1 deletion(-)

 delete mode 100644 b.txt

I then confirmed with git log:

commit c49aa86bd04addb0a585417534bdb02638800e17

Author: James Lavin <james@fakedomain.com>

Date:   Thu Mar 13 16:59:26 2014 -0400

    Revert "create b.txt"

    This reverts commit 31fec743e007f94eb4738d1108c79b38dfa6cff0.

commit 4323ac0c5bccda28fc263ca7c8ff9d4d9f88a14c

Author: James Lavin <james@fakedomain.com>

Date:   Thu Mar 13 16:59:26 2014 -0400

    Revert "create c.txt"

    This reverts commit b59b5ecddc5284358da38635dc0829f629be11a7.

commit b59b5ecddc5284358da38635dc0829f629be11a7

Author: James Lavin <james@fakedomain.com>

Date:   Thu Mar 13 16:58:42 2014 -0400

    create c.txt

commit 31fec743e007f94eb4738d1108c79b38dfa6cff0

Author: James Lavin <james@fakedomain.com>

Date:   Thu Mar 13 16:58:19 2014 -0400

    create b.txt

commit a9d88ae06cedf5296297705142020a5264c839b8

Author: James Lavin <james@fakedomain.com>

Date:   Thu Mar 13 16:57:56 2014 -0400

    create a.txt

To check again, I ran git diff a9d88ae06cedf52 and got blank output, indicating I was where I was after the first commit.

To triple check, I ran ls and saw only the file I added to Git in the first commit:

a.txt

Posted by James on Thursday, March 13, 2014