git - 我如何在 git 中故意分离 HEAD?

标签 git git-checkout

如果我执行 git checkout HEAD^,我会得到:

$ git checkout HEAD^
Note: checking out 'HEAD^'.

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

资深 git 用户可能对此非常熟悉。但是如果我执行 git checkout HEAD,什么也不会发生:

$ git checkout HEAD
$

我想为当前分支头部的提交创建“分离的 HEAD”状态。我该怎么做?

最佳答案

自 git 1.7.5(2011 年 4 月)起,您可以使用 git checkout --detach命令。
( Since Git 2.23 (Q3 2019) ,你会使用 git switch --detach )

参见 commit 326696

checkout : 介绍--detachgit checkout foo^{commit}”的同义词

For example, one might use this when making a temporary merge to test that two topics work well together.


Commit 8ced1aa (git 1.7.11.3,2012 年 7 月)不允许 --detach在未出生的分支上,所以这不会在 null HEAD 上失败:

git checkout --orphan foo
git checkout --detach
git symbolic-ref HEAD

只有即将发布的 git 1.8.4.2 或 1.8.5(2013 年第 4 季度)阐明了语法。 参见 commit 26776c9 :

Separate this case into two syntactical forms, mimicking the way how the DESCRIPTION section shows this usage.
Also update the text that explains the syntax to name the commit to detach HEAD at to clarify.

'git checkout' [--detach] <commit>::

Prepare to work on top of <commit>, by detaching HEAD at it (see "DETACHED HEAD" section), and updating the index and the tree will be the state recorded in the commit plus the local modifications.

  1. When the <commit> argument is a branch name, the --detach option can be used to detach HEAD at the tip of the branch (git checkout <branch> would check out that branch without detaching HEAD).

  2. Omitting <branch> detaches HEAD at the tip of the current branch.

最后一点正是您要为当前分支做的事情:

git checkout --detach

关于git - 我如何在 git 中故意分离 HEAD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13292918/

相关文章:

linux - git:在任何客户端推送后自动在服务器上运行 bash 脚本

git - 如何使用 Git 进行预 checkout

git - 干净的工作树下 `git branch -f <branch_name> <hash>` 和 `git checkout <branch_name>; git reset --hard <hash>` 之间的区别?

git pull U、A 和 D 标签 : Meaning?

git - checkout 并不允许更改 git 中的文件

git - 如何在 Visual Studio 2019 中执行 `git checkout`?

git - 如何将文件重置或还原为特定修订版?

git - 在 Git 中执行的命令的历史记录或日志

java - 更改哪个文件夹是远程 github 存储库的 master 分支

Git:撤消本地更改;混帐添加。 + 混帐室?