Undo a Git merge that hasn't been pushed yet

前端 未结 30 2215
情歌与酒
情歌与酒 2020-11-21 22:27

Within my master branch, I did a git merge some-other-branch locally, but never pushed the changes to origin master. I didn\'t mean to merge, so I\'d like to un

相关标签:
30条回答
  • 2020-11-21 23:16

    Lately, I've been using git reflog to help with this. This mostly only works if the merge JUST happened, and it was on your machine.

    git reflog might return something like:

    fbb0c0f HEAD@{0}: commit (merge): Merge branch 'master' into my-branch
    43b6032 HEAD@{1}: checkout: moving from master to my-branch
    e3753a7 HEAD@{2}: rebase finished: returning to refs/heads/master
    e3753a7 HEAD@{3}: pull --rebase: checkout e3753a71d92b032034dcb299d2df2edc09b5830e
    b41ea52 HEAD@{4}: reset: moving to HEAD^
    8400a0f HEAD@{5}: rebase: aborting
    

    The first line indicates that a merge occurred. The 2nd line is the time before my merge. I simply git reset --hard 43b6032 to force this branch to track from before the merge, and carry-on.

    0 讨论(0)
  • 2020-11-21 23:16

    If branches are murge and not pushed. Then bellow git reset command will work to undo the merge: git reset --merge ORIG_HEAD

    0 讨论(0)
  • 2020-11-21 23:17

    See chapter 4 in the Git book and the original post by Linus Torvalds.

    To undo a merge that was already pushed:

    git revert -m 1 commit_hash
    

    Be sure to revert the revert if you're committing the branch again, like Linus said.

    0 讨论(0)
  • 2020-11-21 23:19

    It can be done multiple ways.

    1) Abort Merge

    If you are in-between a bad merge (mistakenly done with wrong branch), and wanted to avoid the merge to go back to the branch latest as below:

    git merge --abort
    

    2) Reset HEAD to remote branch

    If you are working from remote develop branch, you can reset HEAD to the last commit on remote branch as below:

    git reset --hard origin/develop
    

    3) Delete current branch, and checkout again from the remote repository

    Considering, you are working on develop branch in local repo, that syncs with remote/develop branch, you can do as below:

    git checkout master 
    ##to delete one branch, you need to be on another branch, otherwise you will fall with the branch :) 
    
    git branch -D develop
    git checkout -b develop origin/develop
    
    0 讨论(0)
  • 2020-11-21 23:20

    Just create new branch, then cherry-pick desired commits to it.

    Its saver and simpler then resets described in many answers above

    0 讨论(0)
  • 2020-11-21 23:21

    Assuming your local master was not ahead of origin/master, you should be able to do

    git reset --hard origin/master
    

    Then your local master branch should look identical to origin/master.

    0 讨论(0)
提交回复
热议问题