git checkout <commit>没有显示我的代码的先前版本</commit>

时间:2014-06-16 15:02:58

标签: git

我对git checkout <commit>的理解是,git会将我的工作目录恢复到之前提交时所处的状态。但这根本不是发生的事情。例如:

rwilson@855:~/jt$ cat > x.x
1st line
rwilson@855:~/jt$ git add x.x
rwilson@855:~/jt$ git commit -m "Initial commit"
[master (root-commit) f5df7c2] Initial commit
 1 file changed, 1 insertion(+)
 create mode 100644 x.x
rwilson@855:~/jt$ cat >> x.x
2nd line
rwilson@855:~/jt$ git log --oneline
f5df7c2 Initial commit
rwilson@855:~/jt$ # I want to go back to old version of x.x now
rwilson@855:~/jt$ git checkout f5df7c2
M   x.x
Note: checking out 'f5df7c2'.

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 f5df7c2... Initial commit
rwilson@855:~/jt$ cat x.x
1st line
2nd line

所以我的问题是(1)我如何要求git将我的工作目录置于初始提交后的完全相同的状态? (2)为什么git允许我回到旧的提交但保持本地更改?谁会想要这些旧文件(来自旧提交)和新的非分段更改的混合?似乎非常反直觉。

2 个答案:

答案 0 :(得分:1)

您当前的修改(向x.x添加一行)不会保存在任何地方,也不会与提交f5df7c2不兼容。

因此,git允许您在不删除当前工作树修改的情况下浏览历史记录。两种可能性:

  • 使用git stash暂停您的修改(您可以稍后使用git stack pop
  • 将其修改回来
  • 使用git checkout .完全删除您的修改。使用此命令,您确定您拥有当前提交中的文件(除非您有暂存文件)

答案 1 :(得分:1)

这是因为你没有承诺或隐藏它们。因此,您可以转到之前的提交。

您可以在检出先前提交或git stash之前向文件添加其他行时git commit更改,以便在检出先前提交时看到以前版本的文件