通常,要放弃对文件的更改,你会做:

git checkout -- <file>

如果我想要丢弃的更改是删除文件呢?上面的代码行会给出一个错误:

error: pathspec '<file>' did not match any file(s) known to git.

什么命令可以在不取消其他更改的情况下恢复该单个文件?

另外,如果我想放弃的更改是添加一个文件,该怎么办?我也想知道如何消除这种变化。


当前回答

如果它已经被暂存并提交,那么以下命令将重置该文件:

git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path

这将适用于前几次提交的删除。

其他回答

如果它已经被暂存并提交,那么以下命令将重置该文件:

git reset COMMIT_HASH file_path
git checkout COMMIT_HASH file_path
git add file_path

这将适用于前几次提交的删除。

从git v2.23开始,你有另一个选择:

Git恢复——staging——<文件>

这两个问题都在git状态中得到了回答。

要取消添加新文件,请使用git rm——cached filename.ext

# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
#   new file:   test

要取消删除文件,请使用git reset HEAD filename.ext

# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   deleted:    test

另一方面,git checkout从不取消阶段,它只丢弃非阶段更改。

从手册页,

git-reset - Reset current HEAD to the specified state
git reset [-q] [<tree-ish>] [--] <paths>...
In the first and second form, copy entries from <tree-ish> to the index.

例如,当我们使用git重置HEAD~1 它重置我们当前的头头~1

所以当我们使用git重置'some-deleted-file-path'时

git假设'some-deleted-file-path'作为某个提交点,并尝试将当前HEAD重置到那里。

最终以失败告终

fatal: ambiguous argument 'some-deleted-file-path': unknown revision or path not in the working tree.

假设你想要撤销git rm <file>或rm <file>的效果,然后加上git add -A或类似的东西:

# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>

要撤消git add <file>,上面的第一行就足够了,假设您还没有提交。