如何将git文件还原为暂存区版本?


80

假设我有一个名为的文件a.txt。我将其添加到暂存区域,然后对其进行修改。如何将其恢复为添加时的状态?

Answers:


77
  • 在Git 2.23之前: git checkout a.txt
  • 从Git 2.23开始: git restore a.txt

如果您键入,Git会告诉您git status

在Git 2.23之前:

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# modified:   a
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified:   a
#

从Git 2.23开始:

On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   a

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   a

3
@Daenyth我在发布之前已经检查过它,您可以看到输出显示了以不同状态(暂存或未暂存)重置文件的不同方式
Abyx 2010年

1
@Daenyth-您正在考虑使用“ git checkout分支名称路径”或“ git checkout HEAD路径”
William Pursell,2010年

@威廉:谢谢!现在变得更加有意义。
丹妮丝

不适用于新文件,因此它实际上不需要阶段检查,因为它确实需要对象。如何从登台结帐?编辑它确实--像状态所说的那样工作。
鲁迪2014年

30

git checkout -- a.txt

此页面上的其他答案没有--,并造成了一些混乱。

这是Git在您键入时告诉您的内容git status

# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# modified:   a
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified:   a
#

4
您最好告诉我们区别,而不是发布以前引用的内容。
巴绍(Bachsau)

2

暂存暂存文件

接下来的两节演示了如何使用暂存区和工作目录更改。令人高兴的是,用于确定这两个区域的状态的命令还提醒您如何撤消对它们的更改。例如,假设您已经更改了两个文件,并想将它们提交为两个单独的更改,但是您不小心键入了git add *并将它们暂存。您如何才能解除这两者之一?git status命令提醒您:

$ git add *
$ git status

On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

renamed:    README.md -> README
modified:   CONTRIBUTING.md

在“要提交的更改”文本的正下方,显示使用git reset HEAD ...取消登台。因此,让我们使用该建议取消暂存CONTRIBUTING.md文件:

$ git reset HEAD CONTRIBUTING.md
Unstaged changes after reset:
M   CONTRIBUTING.md

$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

renamed:    README.md -> README

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)

modified:   CONTRIBUTING.md

该命令有点奇怪,但是可以使用。CONTRIBUTING.md文件已修改,但再次未登台。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.