Git:还原我的.gitignore中的文件

时间:2013-03-15 01:09:34

标签: git gitignore

我想将Git中的文件恢复为之前的提交。我的.gitignore文件会忽略该文件。在我最近的提交中,我不小心强迫它。

此问题解答了如何还原任何特定文件:Reset or revert a specific file to a specific revision using Git?

运行:

git checkout 234234234b234234234c123424 build/includes/initialize.php

错误:

error: pathspec 'build/includes/initialize.php' did not match any file(s) known to git.

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您必须指定错误的提交或错误的路径。

$ git init
Initialized empty Git repository in /.../.git/
$ echo test.txt > .gitignore
$ git add .gitignore
[master (root-commit) 6ed8815] Commit 1
 1 file changed, 1 insertion(+)
 create mode 100644 .gitignore
$ git commit -m "Commit 1"
$ echo 'Version 1' > test.txt
$ git add test.txt
The following paths are ignored by one of your .gitignore files:
test.txt
Use -f if you really want to add them.
fatal: no files added
$ git add -f test.txt
$ git commit -m "Commit 2"
[master b23a130] Commit 2
 1 file changed, 1 insertion(+)
 create mode 100644 test.txt
$ echo 'Version 2' > test.txt
$ git add test.txt
$ git commit -m "Commit 3"
[master 60c1f24] Commit 3
 1 file changed, 1 insertion(+), 1 deletion(-)
$ cat test.txt
Version 2
$ git checkout b23a130 test.txt
$ cat test.txt
Version 1

如果输入错误的提交,我会收到以下错误消息:

$ git checkout 6ed8815 test.txt
error: pathspec 'test.txt' did not match any file(s) known to git.

如果输入错误的路径名,我也会收到错误消息:

$ git checkout b23a130 other.txt
error: pathspec 'other.txt' did not match any file(s) known to git.

答案 1 :(得分:0)

错误消息:

error: pathspec 'build/includes/initialize.php' did not match any file(s) known to git

意味着您要么不在包含文件build/includes/initialize.php的存储库中的正确目录中,要么存储文件build/includes/initialize.php实际上不存在于存储库历史记录中的任何位置。

您可以运行git log -- build/includes/initialize.php来验证您是否能够看到修改此文件的提交日志(即使该文件当前已被删除)。如果这不返回任何输出,则确认您位于错误的目录中。

顺便说一下,一旦你把文件添加到git,git会自动跟踪对文件的更改,而不管.gitignore中是否列出了文件。换句话说,后续添加不再需要指定-f