28

I started working on some files I had in a git submodule under another project. However, since it was a git submodule it never checked out "master" and instead just checked out the head and placed all the files in the folder in "no branch".

Now that I've made some changes by accident to these files I just realized that I was working in a "no branch", submodule of my project.

How do I get those files into a branch (like master) so I can rescue them?

3 Answers 3

54

You can use git reflog to find the "lost" commits:

$ cd submodule_dir
$ git reflog          # Find the commit
$ git checkout master
$ git cherry-pick $SHA_OF_MISSING_CMMIT
3
  • Yep, this worked great! except I did a git merge $COMMIT_SHA once I was in the other branch.
    – Xeoncross
    Mar 5, 2010 at 1:18
  • perfect. thank you!
    – Yshmarov
    Sep 6, 2021 at 18:31
  • Great thing to know about. Thanks! Feb 9, 2022 at 14:47
4

The “no branch” state is called a detached HEAD. It is called this because the HEAD ref is not attached to any branch, instead it is pointing directly at a commit. To attach HEAD to a branch that points to the current HEAD commit, use git checkout -b branchname.

You can safely update an existing branch to include the commits at HEAD with this sequence:

git branch temp
git checkout branchname
git merge temp
git branch -d temp

Or, equivalently, using the reflog notation HEAD@{1} to avoid having to make the temporary branch:

git checkout branchname
git merge HEAD@{1}

Using the temporary branch would be a good idea if you were not going to do the merge immediately.

If you want to forcibly overwrite an existing branch to point to the commit at HEAD you can use git branch -f branchname && git checkout branchname. If the commit at HEAD is not based on the current tip of branchname this will result in a non-fast-forward change to branchname which you usually want to avoid (it is viewed as rewriting history).

1
  • Note this answer assumes that the HEAD is still pointing to the last commit-that-was-not-on-a-branch. If you have moved the HEAD since then and only now realized what happened, you may need to look for that lost commit in the reflog (see mipadi's answer).
    – LarsH
    Mar 9, 2018 at 15:00
2

To add to previous answers:

While you're still on a detached HEAD, you can add a tag:

git tag <some-tag>

This will add a tag to the commit, which will make it visible in gitk and other tools.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .