在最后一次提交后,我修改了工作副本中的一堆文件,但我想撤消对其中一个文件的更改,如将其重置为与最近一次提交相同的状态。

然而,我只想撤消仅对该文件的工作副本更改,而不做其他更改。

我该怎么做?


当前回答

您可以使用

git checkout -- file

您可以不使用--(如nimrodm所建议的),但如果文件名看起来像分支或标记(或其他修订标识符),则可能会混淆,因此最好使用--。

您还可以检出文件的特定版本:

git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file         # stable branch
git checkout origin/master -- file  # upstream master
git checkout HEAD -- file           # the version from the most recent commit
git checkout HEAD^ -- file          # the version before the most recent commit

其他回答

如果已经提交,则可以还原文件的更改并再次提交,然后用上次提交来压缩新的提交。

我通过gitbash完成了:

(使用“gitcheckout--<file>…”放弃工作目录中的更改)

Git状态。[所以我们看到一个文件被修改了。]git checkout--index.html[我已在index.html文件中更改:git状态[现在这些更改已删除]

如果您想撤消对该文件的上一次提交更改,可以尝试以下操作:

git checkout branchname^ filename

这将按上次提交前的状态签出文件。如果您想再提交几次,请使用branchname~n表示法。

git还原文件

请参阅此重复答案(确保向下滚动到2020更新):https://stackoverflow.com/a/31281748/12763497

您可以使用

git checkout -- file

您可以不使用--(如nimrodm所建议的),但如果文件名看起来像分支或标记(或其他修订标识符),则可能会混淆,因此最好使用--。

您还可以检出文件的特定版本:

git checkout v1.2.3 -- file         # tag v1.2.3
git checkout stable -- file         # stable branch
git checkout origin/master -- file  # upstream master
git checkout HEAD -- file           # the version from the most recent commit
git checkout HEAD^ -- file          # the version before the most recent commit