How to squash your commits when not being your recent ones

This question already has an answer here:

  • Squash my last X commits together using Git 23 answers

  • This can be done by doing an interactive rebase.

    If you have branch master at commit A , and then you created branch my-branch with commits B , C , D , E , and F . You want to squash commits B , C , and D into B' .

    Make sure your current branch is my-branch , and start an interactive rebase:

    git rebase -i master
    

    This will open your editor with the list of commits that will be acted upon. Each line represents one commit, and the first word on that line says the command to perform on that commit. Leave the first commit ( B ) as pick , and change the commands for the next two commits ( C and D ) to squash . Save and close the editor.

    After git has finished processing commits B , C , and D , a new editor will open with a commit message for the new commit B' . This will contain a combination of the commit messages from the original commits, but you can change it to whatever you'd like. Once the commit message is what you want it to be, save and close the editor.

    Once git has finished processing the rest of the commits on branch my-branch , commits on my-branch will be B' , E , and F .

    Note that you should only do a rebase if you haven't pushed your commits. Rebasing will change the hashes of your commits, which will cause problems if someone else has already pulled the original commits.


    git rebase -i HEAD~6
    

    Then in the interactive editor put squash (you can abbreviate to s ) in front of the commits you want to squash and leave the others as pick .

    Example:

    pick 043af87 message
    s    8c0fa0e message
    s    b6c7116 message
    pick c5d91a3 message
    pick f20898f message
    pick edcbad2 message
    

    If you haven't published the branch, you could rewrite its history without any side effect.

    Suppose the history is ABCDEFGHI and the goal is to squash CDEFG .

    git checkout -b squash_branch G
    git reset C --soft
    git commit
    git cherry-pick H I
    

    The new history will be ABS-H'-I' .

    链接地址: http://www.djcxy.com/p/27620.html

    上一篇: 你怎么git只推新的提交

    下一篇: 如果你不是你最近的那些,就要压缩你的提交