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

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


当前回答

根据我的回答:如何从git存储库中删除目录?

要仅从git存储库中删除文件夹/目录,而不是从本地删除,请尝试3个简单步骤。


删除目录的步骤

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

在下次提交时忽略该文件夹的步骤

要在下次提交时忽略该文件夹,请在根目录中创建一个名为.gitignore的文件并将文件夹名称放入其中。您可以放入任意数量的文件夹

.gitignore文件将如下所示

/FolderName

其他回答

如果您使用的是PowerShell,请尝试将以下命令作为单个命令。

PS MyRepo> git filter-branch --force --index-filter
>> "git rm --cached --ignore-unmatch -r .\\\path\\\to\\\directory"
>> --prune-empty --tag-name-filter cat -- --all

然后,git push-force-all。

文档:https://git-scm.com/docs/git-filter-branch

如果您在windows机器上使用Blundell所描述的技术(删除所有内容,然后添加所有内容),则可能会遇到所有文件都被修改的问题,因为行结尾发生了变化。要避免这种情况,请使用以下命令:

git rm -r --cached .
git config --global core.autocrlf false
git add --renormalize .
git add .

这将从索引中删除所有文件,将git配置为不更改行尾,重新规范行尾,并暂存除.gitignore中指定的文件之外的所有刚刚删除的文件

然后git提交

参考:如何在不更改空格的情况下从.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

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

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

根据我的回答:如何从git存储库中删除目录?

要仅从git存储库中删除文件夹/目录,而不是从本地删除,请尝试3个简单步骤。


删除目录的步骤

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

在下次提交时忽略该文件夹的步骤

要在下次提交时忽略该文件夹,请在根目录中创建一个名为.gitignore的文件并将文件夹名称放入其中。您可以放入任意数量的文件夹

.gitignore文件将如下所示

/FolderName