[英]What is the difference between git checkout . vs git reset --hard HEAD
If I have to undo whatever changes I have done in working branch, 如果我必须撤消在工作分支中所做的任何更改,
git checkout .
git reset --hard HEAD
both commands will take me to the last commit. 这两个命令都会带我到最后一次提交。 What is the difference in both command?
这两个命令有什么区别? And when we should use which command?
而何时应该使用哪个命令?
Any help will be appreciated. 任何帮助将不胜感激。 Thanks in advance.
提前致谢。
Short version: git checkout
only touches your working copy, but git reset --hard
can change what a branch points to. 简短版本:
git checkout
仅涉及您的工作副本,但是git reset --hard
可以更改分支指向的内容。 An example from man git-reset
: 来自
man git-reset
的示例:
Undo a commit, making it a topic branch
$ git branch topic/wip (1)
$ git reset --hard HEAD~3 (2)
$ git checkout topic/wip (3)
1. You have made some commits, but realize they were premature to
be in the "master" branch. You want to continue polishing them in a
topic branch, so create "topic/wip" branch off of the current HEAD.
2. Rewind the master branch to get rid of those three commits.
3. Switch to "topic/wip" branch and keep working.
In your example they're effectively interchangeable, but if you used something besides HEAD
(as in the example from the man page) you can alter history. 在您的示例中,它们实际上是可以互换的,但是如果您使用了
HEAD
以外的其他内容(如手册页中的示例),则可以更改历史记录。
git checkout
will only update the working tree, that is changes which have not yet been staged using git add ...
. git checkout
将仅更新工作树,即尚未使用git add ...
更改。
git reset --hard HEAD
will both update the working tree and the index (staged files). git reset --hard HEAD
将同时更新工作树和索引(暂存文件)。
The more flexible and transparent option is to use git checkout -p
, which will prompt for each section to undo individually, and won't undo changes which have been staged. 更加灵活和透明的选项是使用
git checkout -p
,它将提示每个部分分别撤消,并且不会撤消已暂存的更改。 This is a great choice for undoing bits of code you don't want, while retaining some working tree changes. 这是撤消不需要的代码位,同时保留一些有效的树更改的绝佳选择。 It also forces you to look at what you're deleting, reducing the chance of an unrecoverable mistake.
它还会迫使您查看要删除的内容,从而减少了无法恢复的错误的可能性。
Using reset would be more appropriate when you have a large number of working tree and staged changes that you are absolutely sure you want to undo, such as after an accidental folder deletion or a bad git mv
. 当您有大量工作树并且已确定要撤消的阶段性更改时,例如在意外删除文件夹或
git mv
错误之后,使用reset更为合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.