Git: “Not currently on any branch.” Is there an easy way to get back on a branch, while keeping the changes?

后端 未结 9 580
梦谈多话
梦谈多话 2020-12-12 08:26

So I\'ve done some work in the repository and when I\'m about to commit I realize that I\'m not currently on any branch.

This happens a lot when working with submodu

相关标签:
9条回答
  • 2020-12-12 09:11

    I know I told babay in 2012 that I thought it was unlikely that someone wouldn't realize that they weren't on a branch and commit. This just happened to me, so I guess I have to admit that I was wrong, but considering that it took until 2016 for this to happen to me, you could argue that it is in fact unlikely.

    Anyway, creating a new branch is overkill in my opinion. All you have to do is:

    git checkout some-branch
    git merge commit-sha
    

    If you didn't copy the commit-sha before checking out the other branch, you can easily find it by running:

    git reflog
    
    0 讨论(0)
  • 2020-12-12 09:13

    One way to end up in this situation is after doing a rebase from a remote branch. In this case, the new commits are pointed to by HEAD but master does not point to them -- it's pointing to wherever it was before you rebased the other branch.

    You can make this commit your new master by doing:

    git branch -f master HEAD
    git checkout master
    

    This forcibly updates master to point to HEAD (without putting you on master) then switches to master.

    0 讨论(0)
  • 2020-12-12 09:14

    Leaving another way here

    git branch newbranch
    git checkout master 
    git merge newbranch 
    
    0 讨论(0)
  • 2020-12-12 09:21

    this helped me

    git checkout -b newbranch
    git checkout master
    git merge newbranch
    git branch -d newbranch
    
    0 讨论(0)
  • 2020-12-12 09:22

    The following method may work:

    git rebase HEAD master
    git checkout master
    

    This will rebase your current HEAD changes on top of the master. Then you can switch the branch.


    Alternative way is to checkout the branch first:

    git checkout master
    

    Then Git should display SHA1 of your detached commits, then you can cherry pick them, e.g.

    git cherry-pick YOURSHA1
    

    Or you can also merge the latest one:

    git merge YOURSHA1
    

    To see all of your commits from different branches (to make sure you've them), run: git reflog.

    0 讨论(0)
  • 2020-12-12 09:26

    If you have not committed:

    git stash
    git checkout some-branch
    git stash pop
    

    If you have committed and have not changed anything since:

    git log --oneline -n1 # this will give you the SHA
    git checkout some-branch
    git merge ${commit-sha}
    

    If you have committed and then done extra work:

    git stash
    git log --oneline -n1 # this will give you the SHA
    git checkout some-branch
    git merge ${commit-sha}
    git stash pop
    
    0 讨论(0)
提交回复
热议问题