Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 14 down vote accepted

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
share|improve this answer
Yep, this worked great! except I did a git merge $COMMIT_SHA once I was in the other branch. – Xeoncross Mar 5 '10 at 1:18

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).

share|improve this answer

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.

share|improve this answer

You must log in to answer this question.

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