How to revert the last 2 commits done on Git

Ramji Seetharaman picture Ramji Seetharaman · Jul 12, 2017 · Viewed 16.4k times · Source

I have a situation here where there are 2 commits done by another collaborator which seems to be the wrong files. I am the owner of the repository and would like to revert those 2 commits done by the other collaborator. From my terminal, I tried the following.

git log -2 and it just says the last 2 commits which I did. I want to know how I can reset the last 2 commits and change the HEAD to the commit before those 2.

Answer

Tim Biegeleisen picture Tim Biegeleisen · Jul 12, 2017

Use git revert:

git revert A^..B

where A is hash of the first of the two commits to be reverted and B is the hash of the second commit. This approach will work even if other commits have been made on the remote branch since the two commits were made.

If this branch were not shared with anyone you could also use

git reset --hard HEAD~2

But beware of using git reset --hard on a publicly shared branch. For a shared branch, it is much safer to use git revert as described above.