Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to un-commit last un-pushed git commit without losing the changes

Tags:

git

Is there a way to revert a commit so that my local copy keeps the changes made in that commit, but they become non-committed changes in my working copy? Rolling back a commit takes you to the previous commit - I want to keep the changes made but I committed them to the wrong branch.

This has not been pushed, only committed.

like image 976
Mr. Boy Avatar asked Nov 08 '13 12:11

Mr. Boy


People also ask

How do you Uncommit your last commit but keep changes?

In order to undo the last Git commit, keep changes in the working directory but NOT in the index, you have to use the “git reset” command with the “–mixed” option. Next to this command, simply append “HEAD~1” for the last commit.

How do I Uncommit the last 3 commits?

The git reset command is used to undo changes. Put the corresponding number instead of ~x . For example, if you specify ~3 , the command will affect the three latest commits.

How do I revert my last remote commit?

To undo the last commit from a remote git repository, you can use the git reset command. command. This will undo the last commit locally. command to force push the local commit which was reverted to the remote git repository.


2 Answers

There are a lot of ways to do so, for example:

in case you have not pushed the commit publicly yet:

git reset HEAD~1 --soft    

That's it, your commit changes will be in your working directory, whereas the LAST commit will be removed from your current branch. See git reset man


In case you did push publicly (on a branch called 'master'):

git checkout -b MyCommit //save your commit in a separate branch just in case (so you don't have to dig it from reflog in case you screw up :) ) 

revert commit normally and push

git checkout master git revert a8172f36 #hash of the commit you want to destroy # this introduces a new commit (say, it's hash is 86b48ba) which removes changes, introduced in the commit in question (but those changes are still visible in the history) git push origin master 

now if you want to have those changes as you local changes in your working copy ("so that your local copy keeps the changes made in that commit") - just revert the revert commit with --no-commit option:

git revert --no-commit 86b48ba (hash of the revert commit). 

I've crafted a small example: https://github.com/Isantipov/git-revert/commits/master

like image 95
Isantipov Avatar answered Oct 11 '22 06:10

Isantipov


If you pushed the changes, you can undo it and move the files back to stage without using another branch.

git show HEAD > patch git revert HEAD git apply patch 

It will create a patch file that contain the last branch changes. Then it revert the changes. And finally, apply the patch files to the working tree.

like image 25
Aminadav Glickshtein Avatar answered Oct 11 '22 05:10

Aminadav Glickshtein