108

Consider this scenario:

  1. Developer A does a commit: #n
  2. Dev. B does commit #n+1
  3. Dev. A does commit #n+2
  4. and commit #n+3

and then discovers that in his commit #n+2 he introduced a defect.

How can dev. A rollback his last 2 commits and continue developing on commit #n+1?

Tried git reset --hard HEAD~2*, but it's coming back to dev A's commit #n.

Marius Butuc
  • 17,781
  • 22
  • 77
  • 111
  • 5
    git reset HEAD~2 should reset to #n+1 commit if you have pulled B commits at that point. Did you pulled them? – Snowbear Jan 21 '11 at 20:04
  • 1
    ...not before #n+2 commit. It was: [0] B pushed `commit` #n+1, [1] A `commit`ted #n+2, [2] unsuccessful `push`, [3] `pull`, [4] `push`. So on github now there is a commit (#n+2), and a Merge branch 'master' (#n+3). – Marius Butuc Jan 21 '11 at 20:23
  • 3
    If you have already published the commit, you should not use reset to roll it back. (If some other developer unkown to you has pulled, this will cause pain.) Instead, use revert and make a new commit that brings you to the state that you want. Never change a published history. See http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html – William Pursell Jan 22 '11 at 13:27
  • 2
    Possible duplicate of [How to undo last commit(s) in Git?](http://stackoverflow.com/questions/927358/how-to-undo-last-commits-in-git) – Jim Fell Feb 14 '17 at 18:54

2 Answers2

163

It should come back to the n+1 commit. You probably have a merge commit in there as well. You can also do a git reset --hard <sha1_of_where_you_want_to_be>

WARNING!! --hard means that any uncommitted changes you currently have will be thrown away permanently.

igo
  • 6,359
  • 6
  • 42
  • 51
Adam Dymitruk
  • 124,556
  • 26
  • 146
  • 141
24

I would suggest using instead something like this:

git reset --soft <commit_hash>

Unless you want it to remove all the changes up to that point, in that case use --hard instead of --soft, it would get you to the desired point in the tree WITHOUT trowing away all of the changes made in the commits.

While I was reading I tried with --HARD and for my misfortune, it removed all my changes up to that point. So, pay attention to whether you want them removed or not.

so, if you are unlucky as me try this! : git revert <commit_hash>

Nick Cuevas
  • 1,474
  • 15
  • 10
  • This answer was more helpful than the accepted answer because when I undo changes its usually because I've committed work on the wrong branch. `--soft` is better since I can always delete the files if I so choose. – Dave Thompson May 27 '22 at 13:13
  • Agreed. If you use `--soft`, you can then switch branches and your working directory changes still exist, so you can then do with them whatever you like. – Andy Keith Aug 22 '22 at 15:06
  • This answer was what I was looking for. I reverted my local commit and got my files also. Gave an upvote even though the answer is something else. – Mashmoom Aug 29 '22 at 16:36