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

前端 未结 14 1211
梦毁少年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:19

    Much simpler solution using git stash

    Here's a far simpler solution for commits to the wrong branch. Starting on branch master that has three mistaken commits:

    git reset HEAD~3
    git stash
    git checkout newbranch
    git stash pop
    

    When to use this?

    • If your primary purpose is to roll back master
    • You want to keep file changes
    • You don't care about the messages on the mistaken commits
    • You haven't pushed yet
    • You want this to be easy to memorize
    • You don't want complications like temporary/new branches, finding and copying commit hashes, and other headaches

    What this does, by line number

    1. Undoes the last three commits (and their messages) to master, yet leaves all working files intact
    2. Stashes away all the working file changes, making the master working tree exactly equal to the HEAD~3 state
    3. Switches to an existing branch newbranch
    4. Applies the stashed changes to your working directory and clears the stash

    You can now use git add and git commit as you normally would. All new commits will be added to newbranch.

    What this doesn't do

    • It doesn't leave random temporary branches cluttering your tree
    • It doesn't preserve the mistaken commit messages, so you'll need to add a new commit message to this new commit
    • Update! Use up-arrow to scroll through your command buffer to reapply the prior commit with its commit message (thanks @ARK)

    Goals

    The OP stated the goal was to "take master back to before those commits were made" without losing changes and this solution does that.

    I do this at least once a week when I accidentally make new commits to master instead of develop. Usually I have only one commit to rollback in which case using git reset HEAD^ on line 1 is a simpler way to rollback just one commit.

    Don't do this if you pushed master's changes upstream

    Someone else may have pulled those changes. If you are only rewriting your local master there's no impact when it's pushed upstream, but pushing a rewritten history to collaborators can cause headaches.

提交回复
热议问题