我提交并将一些目录推送到github。之后,我修改了.gitignore文件,添加了一个应该忽略的目录。一切都很好,但(现在被忽略的)目录仍在github上。

如何从github和存储库历史记录中删除该目录?


当前回答

布伦德尔的第一个回答对我来说并不奏效,但它给我指明了正确的方向。我也这样做过:

> for i in `git ls-files -i --exclude-from=.gitignore`; do git rm --cached $i; done
> git commit -m 'Removed all files that are in the .gitignore'
> git push origin master

我建议您先运行以下语句检查要删除的文件:

git ls-files -i --exclude-from=.gitignore

我在visual studio中使用了一个默认的.gitignore文件,我注意到它正在删除项目中的所有日志和bin文件夹,这不是我的本意。

其他回答

.gitignore文件中的规则仅适用于未跟踪的文件。由于该目录下的文件已经提交到您的存储库中,因此您必须将其解压缩,创建提交,并将其推送到GitHub:

git rm -r --cached some-directory
git commit -m 'Remove the now ignored directory "some-directory"'
git push origin master

在不重写存储库历史记录的情况下,您无法从历史记录中删除文件-如果其他人正在使用您的存储库,或者您正在多台计算机上使用它,则不应这样做。如果您仍然想这样做,可以使用gitfilter分支重写历史记录-这里有一个有用的指南。

此外,请注意git-rm-cached-somedirectory的输出类似于:

rm 'some-directory/product/cache/1/small_image/130x130/small_image.jpg'
rm 'some-directory/product/cache/1/small_image/135x/small_image.jpg'
rm 'some-directory/.htaccess'
rm 'some-directory/logo.jpg'

rm是git对存储库的反馈;这些文件仍在工作目录中。

第一种解决方案:

git rm --cached `git ls-files -i -c --exclude-from=.gitignore` 
git commit -m 'Removed all files that are in the .gitignore' 
git push origin main

这将删除git中的所有文件/文件夹,从而避免您必须手动选择每个文件/文件夹


第二种解决方案:它从本地git存储库中删除文件。git rm-r--缓存。git添加。gitcommit-m'删除了.gitignore中的所有文件'git推送原点主

--cached标志从git存储库中删除文件,但不从文件系统中删除。

对于windows用户来说,这对我来说非常有用

git ls-files -i -c --exclude-from=.gitignore | %{git rm --cached $_}
git add .
git commit -m "Remove files from .gitignore"

Blundell的答案应该是有效的,但由于某种奇怪的原因,它与我无关。我必须首先将第一个命令输出的文件名导入一个文件,然后循环该文件并逐个删除该文件。

git ls-files -i --exclude-from=.gitignore > to_remove.txt
while read line; do `git rm -r --cached "$line"`; done < to_remove.txt
rm to_remove.txt
git commit -m 'Removed all files that are in the .gitignore' 
git push origin master

注意:此解决方案仅适用于Github桌面GUI。

使用Github桌面GUI非常简单。

暂时将文件夹移动到其他位置(从项目文件夹中移出)。编辑.gitignore文件并删除文件夹条目,该条目将在github页面上删除主存储库。提交并同步项目文件夹。将文件夹重新移动到项目文件夹中重新编辑.gitignore文件。

这就是全部。