Git how to revert a commit but remember the work?
I am working on a upgrade for a project. I forgot to create a new branch before making the change.
I had commited several times:
Original -> commit -> commit -> commit -> now
Now there is a urgent bug need to be fixed for the original copy, so I want to modify it base on the original one. I am thinking if I revert the change, all the work might lost. Does it still remember the change?
2 Solutions collect form web for “Git how to revert a commit but remember the work?”
Here’s what you can do. First, make a new branch that points to your current work:
git branch project_upgrade
(If you have any uncommitted changes, commit them before you do that.)
Then, while still on your
master branch, go ahead and reset back to before your changes:
git reset --hard <SHA of original commit>
This will reset your
master branch, but leave the
project_upgrade branch pointing to your original work. (Because this will reset all the files, it’s important to make sure that you didn’t have uncommitted changes before branching, so that all your upgrade work will be saved in the commits pointed to by the branch you make.)
Then do your bug fix. Afterwards, you can merge your upgrade work back in:
git merge project_upgrade
I’d do the following, assuming
master now points at
now and you want to point
master back at
// Make sure you are on master, thus looking at 'now' git checkout master // Make a new branch pointing at 'now' git branch new_feature // Reset 'master' back 4 commits to 'original'. git reset --hard HEAD~4
That will leave master back where you want it, and you can make a new commit with your fix on it. Then you can keep working on your new feature by doing
git checkout new_feature. Then check your feature is ready, you can merge it back into master.
Generally you don’t want to develop new features on master for exactly this reason, so while you could immediately merge your new features back into master, I would recommend instead that you
git checkout new_feature and continue your work there until it is done, before you merge.