如何从在git中丢失的commit中恢复代码?

3

我使用 git checkout "commit number1" 回滚到先前的提交。然后我没有意识到我不在任何分支上,所以我在此处进行了更改并将代码提交到 "commit number1"。 现在我切换到特性分支 feature/branch1,但是我看不到任何代码。 如果我切换回 "commit Number1",我也看不到那里的代码。 我是否与任何内容分离?

$ git checkout 49da8b4d431

Note: checking out '49da8b4d431'.

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

我该如何恢复代码?我的代码去哪了?


从远程仓库拉取你想要的分支,使用命令 git pull。 - The One and Only ChemistryBlob
这是你需要做的完整描述。https://dev59.com/ulsW5IYBdhLWcg3w2qNM#34519716 - CodeWizard
2个回答

6

输入git reflog命令,将显示最近提交的所有列表。 找到消息为"commit number1"的提交,然后记录此提交的SHA-1哈希值(看起来像是一个由随机字母数字组成的字符串,长度为7个字符,例如s73nd9a)。

要将此提交合并到您的特性分支中,一种选择是使用git cherry-pick。请尝试以下操作:

git checkout feature/branch1
git cherry-pick s73nd9a

这将应用您在分离头状态下进行的单个提交。请记住,cherry pick 实质上是一个提交合并操作,因此您可能会遇到冲突。


谢谢你,@Tim。这非常有帮助。 - zachandcode

3

git reflog 命令可以展示你 HEAD 的历史记录。查看它以找到你在 "commit number1" 上面做出的提交的 SHA。当你知道 SHA 后,就可以在需要的位置使用 cherry-pick 命令。


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