Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to revert the last 2 commits done on Git

Tags:

git

git-revert

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.

like image 567
Ramji Seetharaman Avatar asked Jul 12 '17 02:07

Ramji Seetharaman


People also ask

Can we revert two commits in git?

To revert multiple commits in the middle of the history, use an interactive rebase. Find the last commit's hash containing all the commits you want to remove. Start an interactive rebase session with git rebase -i <hash>. In the interactive rebase edit screen, remove the commit lines you want to remove.

Can we revert the last commit in git?

The revert command You can find the name of the commit you want to revert using git log . The first commit that's described there is the last commit created. Then you can copy from there the alphanumerical name and use that in the revert command.


2 Answers

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.

like image 69
Tim Biegeleisen Avatar answered Sep 27 '22 20:09

Tim Biegeleisen


Try this but be sure of what you want to do

git reset --hard HEAD~2

git reset --hard is an irreversible change. Also it may be a good time to learn about git reset --hard/--soft/ --mixed

enter image description here

I would also suggest going through this

like image 37
Zakir Avatar answered Sep 27 '22 20:09

Zakir