Git:如何从“分离的HEAD”状态返回


217

如果要结帐一个分支:

git checkout 760ac7e

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

Answers:


331

如果您记得之前已签出了哪个分支(例如master),则只需

git checkout master

拿到了分离的头的状态。

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

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

git checkout -

这也会尝试签出您最后签出的分支。


17
git checkout --杀手级功能!
dimpiax

1
如果不这样git checkout -b new_branch_name做,是否会丢失处于分离HEAD状态的提交?
jocassid

2
@jocassid是的。它们存在一段时间,但git gc运行时将被永久删除。git reflog只要它们还在,您就可以观看它们。
eckes

如果这样做,您是否会丢失在独立HEAD中所做的任何提交/更改?这不是更好的方法吗?stackoverflow.com/a/61489179/13087176
醉意boopenstein

@tipsyboopenstein正确。jocassid已经提到了这一点:stackoverflow.com/questions/11801071/...
eckes

16

使用git reflog发现以前签出的提交的哈希值。

进入最后一个签出分支的快捷方式命令(不确定此方法是否适用于分离的HEAD和中间提交) git checkout -


4

我遇到了这种情况,在该情况下,我检出了文件目录结构不同的先前版本的代码:

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

1

您可能在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到所需的任何分支中,这样就不会丢失提交。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.