使用新的gitignore文件重新同步git repo

Chr*_*ård 180 git

更新gitignore文件后是否可以"刷新"git存储库?

我刚刚向我的gitignore添加了更多的ignorations(?),并希望删除与新文件匹配的repo中的内容.

Von*_*onC 346

" .gitignore文件中没有忽略 "中提到的解决方案有点极端,但应该有效:

# rm all files
git rm -r --cached .
# add all files as per new .gitignore
git add .
# now, commit for new .gitignore to apply
git commit -m ".gitignore is now working"
Run Code Online (Sandbox Code Playgroud)

(确保首先提交您想要保留的更改,以避免任何事件,如下面的jball037 评论.
--cached选项将保持您的文件不受影响.)

您还可以在博客文章" 使Git忽略已跟踪的文件 "中使用其他更细粒度的解决方案:

git rm --cached `git ls-files -i --exclude-standard`
Run Code Online (Sandbox Code Playgroud)

巴西姆在他的编辑中建议:

其路径中包含空格的文件

如果您收到错误消息fatal: path spec '...' did not match any files,可能是路径中有空格的文件.

您可以使用以下选项删除所有其他文件--ignore-unmatch:

git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`
Run Code Online (Sandbox Code Playgroud)

但是不匹配的文件将保留在您的存储库中,并且必须通过用双引号括起它们的路径来显式删除它们:

git rm --cached "<path.to.remaining.file>"
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚跑了这个,丢失了所有未提交的修改,几乎宣布了我的辞职.这个线程上接受的答案挽救了我的生命:http://stackoverflow.com/questions/2125710/how-to-revert-a-git-rm-r (3认同)
  • @ jball037好.我添加了警告并相应地编辑了答案. (3认同)
  • @VonC抱歉,这并不意味着咆哮或坚持:)但是,我使用了--cached,当我检查我的文件时,所有未提交的更改都丢失了.惊慌片刻,但"git reset HEAD"恢复了我的文件(但这次没有我在.gitignore中指定的文件,所以你的解决方案仍然有效!) (2认同)

gra*_*hus 9

我可能会误解,但您是否正在尝试删除新忽略的文件,或者您是否要忽略对这些文件的新修改?在这种情况下,事情正在发挥作用.

如果要删除先前提交的忽略文件,请使用

git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'
Run Code Online (Sandbox Code Playgroud)