New commits aren't on the head
Long story short*, I did some things with my git repository that I don't know how to do, and开发者_StackOverflow中文版 ended up detaching my head, that is, when I commit master
isn't up to date.
How can I fix this? Do I have to merge? (If so, what are the exact commands I want to run?)
When I run git branch, it tells me I'm currently on no branch
$ git branch
* (no branch)
master
- Longer story is that I tried to undo some commits and had no idea how I was supposed to do that. I guess that wasn't too long.
Easiest (safe) way would be to create a temporary branch pointing to your HEAD, checkout master, merge the temporary branch, and then delete it:
git branch temp
git checkout master
git merge temp
git branch -d temp
You could also avoid using the temp branch, and just use the reflog to get the commits from no branch:
git checkout master
git merge HEAD@{1}
HEAD@{1}
here refers to the previous commit that you had checked out; HEAD@{0}
is the same as HEAD
, the current commit that you are working from. If you want to see all of the previous commits that HEAD
has pointed to (that haven't yet expired), you can do:
git reflog
You said that this happened because you were trying to undo commits. As mletterle points out, you can do this with a git reset
. git reset --hard rev
will set the branch you're on, HEAD, your index, and your working copy to a particular revision. Note that this will blow away uncommitted changes, so only do it if you really know what you're doing. Safer would generally be to do git reset rev
, which doesn't affect your working copy, and then selectively revert individual files in your working copy with git checkout
, in order to ensure that you don't accidentally destroy some work you were doing.
Also, git reset
should generally only be used only on unpushed commits. If you are trying to undo something that has already been pushed, and other people have already merged, you generally want git revert
.
There are few ways you can end up on (no branch), but essentially its a junk branch used for examining things, e.g. old commits. If you mistakenly edited files on (no branch), you can switch back to master just as you would from any other branch with changes. Check out the help for git-checkout, but you're going to want to do something like git-checkout -m
to move back to master and merge your current index along with it.
I like Brian Campbell's answer. As for undoing commits, git reset --hard rev should be what you were looking for. http://git-scm.com/docs/git-reset
Maybe you should just go back to the branch you were working on. If it was master it would be
$ git checkout master
精彩评论