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

是否有可能在更新gitignore文件后“刷新”git存储库?

我刚刚添加了更多的ignorations(?)到我的gitignore,并想删除已经在回购匹配新文件的东西。

134488 次浏览

.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"

(确保首先提交您想要保留的更改,以避免任何事件,如jball037 下面的评论
--cached选项将保持你的文件在你的磁盘上不动。

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

git rm --cached `git ls-files -i --exclude-standard`

Bassim表示在他的编辑中:

路径中有空格的文件

如果您得到类似fatal: path spec '...' did not match any files的错误消息,则可能存在路径中有空格的文件。

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

git rm --cached --ignore-unmatch `git ls-files -i --exclude-standard`

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

git rm --cached "<path.to.remaining.file>"

我可能误解了,但是您是试图删除新忽略的文件还是要忽略对这些文件的新修改?在这种情况下,这是可行的。

如果你想删除之前提交的被忽略的文件,那么使用

git rm –cached `git ls-files -i –exclude-standard`
git commit -m 'clean up'

我知道这是一个老问题,但如果文件名包含空格,gracchus的解决方案就不管用了。VonC对带空格的文件名的解决方案是不使用--ignore-unmatch删除它们,然后手动删除它们,但如果有很多,这将不会很好地工作。

下面是一个利用bash数组捕获所有文件的解决方案。

# Build bash array of the file names
while read -r file; do
rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)


git rm –-cached "${rmlist[@]}"


git commit -m 'ignore update'