290

如果要结帐一个分支:

git checkout 760ac7e

例如,如何在不知道其 SHA1的情况下b9ac70b回到最后一个已知的头部?b9ac70b

4

5 回答 5

454

如果您记得之前签出了哪个分支(例如master),您可以简单地

git checkout master

摆脱分离的 HEAD状态。

一般来说:git checkout <branchname>会让你摆脱困境。

如果您不记得最后一个分支名称,请尝试

git checkout -

这也会尝试检查您上次签出的分支。

于 2012-08-03T18:20:13.767 回答
20

用于git reflog查找以前签出的提交的哈希值。

一个快捷命令可以到达你最后一次签出的分支(不确定这是否可以在分离的 HEAD 和中间提交中正常工作)是git checkout -

于 2012-08-03T18:13:22.770 回答
7

我遇到了这种极端情况,我检查了以前版本的代码,其中我的文件目录结构不同:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

在这种情况下,您可能需要使用 --force (当您知道返回原始分支并丢弃更改是安全的事情时)。

git checkout master不工作:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force(或git checkout master -f)工作:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
于 2017-04-10T09:41:47.180 回答
3

你可能在该detached HEAD州做了一些新的提交。我相信如果您按照其他答案的建议进行操作:

git checkout master
# or
git checkout -

那么你可能会失去你的承诺!相反,您可能想要这样做:

# you are currently in detached HEAD state
git checkout -b commits-from-detached-head

然后合并commits-from-detached-head到你想要的任何分支,这样你就不会丢失提交。

于 2020-04-28T20:13:13.323 回答
0

以防万一有人和我有相同的边缘情况:我有一个名为的分支test,并试图创建一个名为test/my-experimental-feature. 这让 git 感到困惑,因为它认为我指的是一个已经存在的分支。我把它改成了test--my-experimental-feature,它工作得很好。

于 2021-12-21T13:13:38.513 回答