如何从git中丢失提交中恢复代码?

时间:2016-08-30 16:52:21

标签: git

我使用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

我如何恢复代码?我的代码到底了吗?

2 个答案:

答案 0 :(得分:3)

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

要将此提交带入您的功能分支,一个选项是使用git cherry-pick。请尝试以下方法:

git checkout feature/branch1
git cherry-pick s73nd9a

这将应用您在分离头状态下进行的单个提交。请记住,一个樱桃选择本质上是一个提交的合并,因此你可能会遇到冲突。

答案 1 :(得分:1)

git reflog会显示HEAD的历史记录。查看它以查找在"commit number1"之上进行的提交的SHA。当你知道SHA时,你可以在你需要的地方挑选它。

相关问题