Search code examples
gitgit-revert

How to revert the last 2 commits done on Git


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.


Solution

  • 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.