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

338

如果想从某个分支切换到特定的提交:

git checkout 760ac7e

假设当前在提交 b9ac70b,如何返回到上一次所知道的头部提交 b9ac70b 而不需要知道其 SHA1 值?

9个回答

526

如果你记得之前检出的分支是哪个(例如master),那么你可以简单地执行以下操作:

git checkout master

要退出“detached HEAD”状态,通常来说:使用git checkout <branchname>即可。

如果你记不得上一个分支的名字,可以尝试:

git checkout -

这也尝试着检出你上次检出的分支。


59
git checkout - 是一个非常方便的功能!它可以让你回到上一次所在的分支。 - dimpiax
1
如果您在分离 HEAD 状态下没有执行 git checkout -b new_branch_name,那么您会失去在此期间所做的提交吗? - jocassid
2
@jocassid 是的,你需要。它们存在一段时间,但当运行 git gc 时,它们将永远被删除。只要它们仍然存在,您可以使用 git reflog 查看它们。 - eckes
@tipsyboopenstein 正确。jocassid已经提到了这一点:https://dev59.com/sWgt5IYBdhLWcg3w0wkk#f_fqnYgBc1ULPQZFkG-_ - eckes
@dimpiax 哈哈,我不知道有 git switch 这个命令。 - mfaani
显示剩余8条评论

21

使用 git reflog 查找以前检出的提交哈希值。

一个快捷命令以跳转到您最后检出的分支(不确定在分离的 HEAD 和中间提交下是否正常工作)是 git checkout -


11
您可能已经在“分离的 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合并到你想要的任何分支中,这样你就不会丢失提交记录。


在某些git版本中,“git checkout master”不再适用,但“git checkout -”适用。 - Mars

8

我遇到了一个特殊情况,当时我检出了代码的一个早期版本,那个版本中我的文件目录结构不同:

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
一般而言:git checkout <branch*>git checkout master是特殊情况)。 *我们(无意中)分离了一个提交(使用git checkout <commit_hash>

0
万一有人和我一样遇到了同样的边缘情况:我有一个名为test的分支,试图创建一个名为test/my-experimental-feature的分支。这让git感到困惑,因为它认为我正在引用一个已经存在的分支。我将其更改为test--my-experimental-feature,然后就可以正常工作了。

0

git switch master 命令用于切换到 "master" 分支。
git switch - 命令用于切换回上一个分支。


-1

由于GitHub不再将master作为新存储库的默认分支。

git checkout master对我无效。

有效的方法是:
git checkout main


-3

git checkout main

这是在我的情况下唯一有效的方法。其他人都是骗子。


还有其他可能性,你可以查看任何分支,而不仅仅是主分支。 - UpAndAdam
答案完全错误 - UpAndAdam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接