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

后端 未结 9 581
梦谈多话
梦谈多话 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:28

    I recently ran into this problem again. It's been a while since I last worked with submodules and having learned more about git I realized that simply checking out the branch you want to commit on is sufficient. Git will keep the working tree even if you don't stash it.

    git checkout existing_branch_name
    

    If you want to work on a new branch this should work for you:

    git checkout -b new_branch_name
    

    The checkout will fail if you have conflicts in the working tree, but that should be quite unusual and if it happens you can just stash it, pop it and resolve the conflict.

    Compared to the accepted answer, this answer will save you the execution of two commands, that don't really take that long to execute anyway. Therefore I will not accept this answer, unless it miraculously gets more upvotes (or at least close) than the currently accepted answer.

    0 讨论(0)
  • 2020-12-12 09:32
    git checkout master
    

    That's result something like this:

    Warning: you are leaving 2 commits behind, not connected to
    any of your branches:
    
    1e7822f readme
    0116b5b returned to clean django
    
    If you want to keep them by creating a new branch, this may be a good time to do so with:
    git branch new_branch_name 1e7822f25e376d6a1182bb86a0adf3a774920e1e
    

    So, let's do it:

    git merge 1e7822f25e376d6a1182bb86a0adf3a774920e1e
    
    0 讨论(0)
  • 2020-12-12 09:32

    Alternatively, you could setup your submodules so that rather than being in their default detached head state you check out a branch.

    Edited to add:

    One way is to checkout a particular branch of the submodule when you add it with the -b flag:

    git submodule add -b master <remote-repo> <path-to-add-it-to>
    

    Another way is to just go into the submodule directory and just check it out

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