我看到几乎每个人都建议创建一个临时分支的解决方案。现在,必须承认,每当出现“以分离状态提交”的问题时,通常是在提交后检测到的。为了那仅有的一次提交就创建一个完整的分支 - 听起来太过繁琐了吧?特别是在您已经在众多分支中跳转的项目中。
那么,有什么简单的方法呢?使用提交哈希值!
如何获取哈希值?
1. 进行 `git log` 命令,您会看到类似以下内容的信息:
commit 10bf8fe4d17bb7de59586a7abb6db321f0786bb3 (HEAD)
Author: Someone <someone@something.com>
Date: So/me/day SO:ME:TI:ME
A commit message that doesn't mean much
commit a3cd1cedf1962916cdc2945f2bd2b271ec8b919d (origin/master, master)
Author: Someone <someone@something.com>
Date: Some/other/day SOME:OTHER:TIME
Another commit message that doesn't mean much
commit 1bfabbe09c70419070fe29ff1ed276c0207bbe10
Author: Someone <someone@something.com>
Date: Thu Jul 8 08:38:12 2021 +0530
Enough reading the example, focus on the answer!!
现在,尽管它看起来像一个普通的情况,但当你执行git push
时,它会显示“Everything up-to-date”。
仔细的人会发现这并不是“up-to-date”。HEAD
在主分支之外。
- 那么,接下来呢?只需复制哈希的初始字符
10bf8fe4d1
。首先,执行git checkout master
,这将把您移动到master
分支。现在,由于您已经复制了哈希值,您可以执行git merge <hash>
。现在执行git log
然后,您会看到:
commit 10bf8fe4d17bb7de59586a7abb6db321f0786bb3 (HEAD -> master)
Author: Someone <someone@something.com>
Date: S/om/eday SO:ME:TI:ME
A commit message that doesn't mean much
commit a3cd1cedf1962916cdc2945f2bd2b271ec8b919d (origin/master)
Author: Someone <someone@something.com>
Date: Some/other/day SOME:OTHER:TIME
Another commit message that doesn't mean much
commit 1bfabbe09c70419070fe29ff1ed276c0207bbe10
Author: Someone <someone@something.com>
Date: Thu Jul 8 08:38:12 2021 +0530
Enough reading the example, focus on the answer!!
现在,HEAD
看起来已经放置在正确的位置了。
有人可能会问:“如果我没有哈希值呢?我对悬空提交一无所知,只是执行了 git checkout master
。” 不用担心,我给你准备好了。你可以在两个地方找到提交哈希值:
- 当你执行
git checkout master
时,git
会像这样警告你
Warning: you are leaving 1 commit behind, not connected to
any of your branches:
10bf8fe A commit message that doesn't mean much
If you want to keep it by creating a new branch, this may be a good time
to do so with:
git branch <new-branch-name> 10bf8fe
Switched to branch 'master'
你能看到你的宝藏(hash
),对吧?
- 别告诉我你找不到它。它就在那儿。但如果你真的找不到,那么可以使用
git reflog
命令。它会展示类似这样的信息:
a3cd1ce (HEAD -> master, origin/master) HEAD@{0}: checkout: moving from 10bf8fe4d17bb7de59586a7abb6db321f0786bb3 to master
10bf8fe HEAD@{1}: commit: A commit message that doesn't mean much
你看,这里是你一直在寻找的宝藏... 哈希值。
我猜这包含了在分离状态下和悬挂提交时可能发生的所有情况。下次要小心!!