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
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
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
.
Leaving another way here
git branch newbranch
git checkout master
git merge newbranch
this helped me
git checkout -b newbranch
git checkout master
git merge newbranch
git branch -d newbranch
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
.
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