2013-03-15 109 views
1

我想將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.

有沒有想法?

+0

您是否嘗試從.gitignore中刪除該文件? – 2013-03-15 01:11:07

+0

您確定您位於git repostitory下的正確目錄中嗎?你能確認'git show 234234234b234234234c123424'返回一個有效的輸出嗎?請注意,您需要將文件的相對位置(從當前位置)或文件的絕對路徑提供給'git checkout'命令,並且您需要位於屬於git存儲庫的目錄中。 – Tuxdude 2013-03-15 01:21:35

+0

如果該文件被忽略,是不是未跟蹤?如果你強制'添加'它,我認爲你應該'git重置FILE'來恢復添加。我不知道你是否也想刪除文件。 – mgarciaisaia 2013-03-15 01:28:05

回答

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. 
+0

該文件已經存在。我需要從提交之前返回到'initialize.php'版本。 – 2013-03-15 01:16:19

+0

@DonnyP:然後你必須指定錯誤的提交。 'git checkout'工作正常。 – 2013-03-15 01:19:33

+0

是否有可能,因爲這個文件被忽略了10次提交,我需要返回11次提交併恢復? – 2013-03-15 01:36:33

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