Move the most recent commit(s) to a new branch with Git

前端 未结 14 1234
梦毁少年i
梦毁少年i 2020-11-22 03:28

I\'d like to move the last several commits I\'ve committed to master to a new branch and take master back to before those commits were made. Unfortunately, my Git-fu is not

14条回答
  •  难免孤独
    2020-11-22 04:15

    In General...

    The method exposed by sykora is the best option in this case. But sometimes is not the easiest and it's not a general method. For a general method use git cherry-pick:

    To achieve what OP wants, its a 2-step process:

    Step 1 - Note which commits from master you want on a newbranch

    Execute

    git checkout master
    git log
    

    Note the hashes of (say 3) commits you want on newbranch. Here I shall use:
    C commit: 9aa1233
    D commit: 453ac3d
    E commit: 612ecb3

    Note: You can use the first seven characters or the whole commit hash

    Step 2 - Put them on the newbranch

    git checkout newbranch
    git cherry-pick 612ecb3
    git cherry-pick 453ac3d
    git cherry-pick 9aa1233
    

    OR (on Git 1.7.2+, use ranges)

    git checkout newbranch
    git cherry-pick 612ecb3~1..9aa1233
    

    git cherry-pick applies those three commits to newbranch.

提交回复
热议问题