How do I delete unpushed git commits?

前端 未结 7 961
轮回少年
轮回少年 2020-11-28 16:45

I accidentally committed to the wrong branch. How do I delete that commit?

相关标签:
7条回答
  • 2020-11-28 17:42

    Don't delete it: for just one commit git cherry-pick is enough.

    But if you had several commits on the wrong branch, that is where git rebase --onto shines:

    Suppose you have this:

     x--x--x--x <-- master
               \
                -y--y--m--m <- y branch, with commits which should have been on master
    

    , then you can mark master and move it where you would want to be:

     git checkout master
     git branch tmp
     git checkout y
     git branch -f master
    
     x--x--x--x <-- tmp
               \
                -y--y--m--m <- y branch, master branch
    

    , reset y branch where it should have been:

     git checkout y
     git reset --hard HEAD~2 # ~1 in your case, 
                             # or ~n, n = number of commits to cancel
    
     x--x--x--x <-- tmp
               \
                -y--y--m--m <- master branch
                    ^
                    |
                    -- y branch
    

    , and finally move your commits (reapply them, making actually new commits)

     git rebase --onto tmp y master
     git branch -D tmp
    
    
     x--x--x--x--m'--m' <-- master
               \
                -y--y <- y branch
    
    0 讨论(0)
提交回复
热议问题