Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

revert the git last commit and save it in a different branch

Is there a way to rollback the last commit and put it into a separate branch for later testing? I did some changes which I don't want to entirely throw away, I just want to keep them aside in a different branch for further testing.

Can anyone help me with this?

like image 955
Mo J. Mughrabi Avatar asked Nov 17 '13 16:11

Mo J. Mughrabi


People also ask

How do you revert a commit from another branch?

Make sure you are on the branch to which you have been committing. Use git log to check how many commits you want to roll back. Then undo the commits with git reset HEAD~N where “N” is the number of commits you want to undo. Then create a new branch and check it out in one go and add and commit your changes again.

How do I revert Last commit and keep changes?

Simply right-click on the commit from the central graph and select Reset -> Soft to keep all of the changes, or Reset -> Hard to discard the changes, if you're sure you won't need them again in the future.

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. In this image, each circe represents a commit.


2 Answers

Yes you can achieve this - branch away from the current branch and create a new branch to preserve the commit, checkout back to the original branch, and then rollback the commit in the original branch.

So from your current branch, (lets call it current), create and checkout a new branch separate

git checkout -b separate

This will create a new branch separate which will have the new commit. Now go back to the original branch

git checkout current

On this branch, you can now rollback the last commit

git reset --hard HEAD~1

If you later want to access that older commit, you have to do a git checkout separate and the commit should be available in that branch.

like image 178
Anshul Goyal Avatar answered Oct 12 '22 22:10

Anshul Goyal


You can do this in two steps and without switching between branches. Here we go.

  1. Create a new branch from the current branch, to set aside your current state:

    git branch feature_maybe
    
  2. Revert the last commit in the current branch:

    git reset --hard HEAD^
    
like image 38
janos Avatar answered Oct 13 '22 00:10

janos