Search code examples
gitgit-revert

How do I revert to the previous commit without deleting the latest commit?


Say I have 2 commits which I have already pushed to my remote branch.

  • Commit A (31-May-2021)
  • Commit B (30-May-2021)

How do I revert to Commit B without deleting Commit A? I just want to compare the result between these 2 commits.

Note: Code comparison is not needed. I just want to compare the output of Commit A vs Commit B


Solution

  • I strongly disagree with the other answers advising you to use git revert. This would actually really revert the changes introduced by Commit A and produce a commit on its own.

    Since you want to have a look at the state at a point back in time, you could just checkout Commit B directly so you can inspect the contents. Afterwards checkout the original branch to go back to the latest commit.

    git checkout $HASH_OF_COMMIT_B   # now you are in a detached head state at commit B
    git checkout $BRANCH             # now you are back at the tip of the branch (commit A)
    

    A lot of tools let you see the difference between two references directly without the need to checkout. On the command line, this could be done with git diff:

    git diff $HASH_OF_COMMIT_A..$HASH_OF_COMMIT_B