10

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?

godel9
  • 7,340
  • 1
  • 33
  • 53
Mo J. Mughrabi
  • 6,747
  • 16
  • 85
  • 143

3 Answers3

19

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.

Community
  • 1
  • 1
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • 1
    anash0l the approach works well, locally, but when I tried to push to github it didn't go through.. any idea what am missing? – Mo J. Mughrabi Nov 17 '13 at 17:31
  • @MoJ.Mughrabi Had you already pushed to github (before doing these operations)? Could someone else have pulled in the changes? – Anshul Goyal Nov 17 '13 at 17:33
  • @anash0l yeah i did, but i have deployment scripts which tries to pull and they don't see the new revert action. As I used "push -f" to get the changes through to github – Mo J. Mughrabi Nov 17 '13 at 17:38
  • @MoJ.Mughrabi okay, do you want to push branch `separate` as well? In that case, do `git push origin separate`. That should create a new branch `separate` on github as well. – Anshul Goyal Nov 17 '13 at 17:39
4

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^
    
janos
  • 120,954
  • 29
  • 226
  • 236
0

Yes - check out a new branch using git checkout -b <new branch name>, switch to the original branch using git checkout <original branch name>, then do git reset --hard HEAD~1 to move the original branch back a commit. (As always when moving branches around, it's safest to visualise what you're doing step-by-step using a program like gitk.)

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80