How to undo a commit and commit the changes into the other branch in Git?

后端 未结 3 565
醉话见心
醉话见心 2021-01-01 04:41

The common mistake I make in git is

  1. not check on which branch I am
  2. commit changes to a wrong branch (on branch B, thinking I\'m on A, commiting a chan
3条回答
  •  -上瘾入骨i
    2021-01-01 05:08

    Checkout the wrong branch where the commit is

    git checkout wrong_branch
    

    In the wrong branch, reset to the previous commit:

    git reset --hard HEAD^
    

    NOTE: the ^ operator indicating the previous commit, to remove multiple commits use ~N where N is the number of commits

    Checkout to the branch where the commit should be

    git checkout right_branch
    

    Re-apply the commit using cherry-pick

    git cherry-pick wrong_branch@{1}
    

    NOTE: wrong_branch@{1} is the last commit of wrong_branch before the git reset command was executed, for example, HEAD@{2} could be used too in this case

    To move multiple commits you could use multiple calls to git cherry-pick or only one execution of git rebase:

    git rebase --onto right_branch wrong_branch@{1}~N wrong_branch@{1}
    

    (and the corresponding parameter to reset will be HEAD~N in this case)

提交回复
热议问题