从 Git 仓库中删除已提交的文件

3
我已经将两个目录推送到我的Git Bitbucket代码库中,现在我希望将它们删除。请问如何进行这些更改?我已经尝试过以下操作:
git rm -rf --cached files 
git commit -a -m "Deleted files" 
git push origin master

我理解的是它只从我的工作目录中删除了文件,但保留了在Bitbucket中的原样。

也许您可以还原添加这些目录的提交? - toniedzwiedz
相关内容:https://dev59.com/lnM_5IYBdhLWcg3w-4dg - Sascha Wolf
4个回答

5
您可以通过以下命令还原推送这些目录时使用的提交:
git reset --soft HEAD^

假设不需要的提交在 HEAD 的顶部。

如果它位于某些提交之前,请尝试以下操作:

git reset --soft HEAD~3

这将撤销HEAD中倒数第四个提交所做的更改。(根据您不需要的提交的位置,您需要更改数字“3”)

然后检查git status。您应该能够看到那些不需要的目录作为您的本地更改,尚未提交。

谢谢!


@nicoX,如果您发现这个解决方案很有帮助,请不要犹豫地“接受”这个答案。这样,它也会对未来的读者有所帮助! - Breen ho

1

我不久前也遇到了类似的问题,我使用交互式变基解决了它。

你需要做的是找到要更改的提交之前的提交哈希值。假设该哈希值为376c762c1b28f927595010e98e4ee82d6bc63de3

# first git checkout the correct branch
git rebase -i 376c762c1b28f927595010e98e4ee82d6bc63de3

然后您会得到一个列表,其中包含提交哈希之后的所有提交以及部分提交消息。

pick 376c762 Commit with wrong file
pick e145ef2 Fourth before last commit
pick d969e5b Third before last commit
pick 7b92c09 Second before last commit
pick db1dea3 First before last commit
pick ff120d6 Most recent commit message

# Rebase 621d70a..ff120d6 onto 621d70a (6 commands)
#
# Commands:
# p, pick <commit> = use commit
# r, reword <commit> = use commit, but edit the commit message
# e, edit <commit> = use commit, but stop for amending
# s, squash <commit> = use commit, but meld into previous commit
# f, fixup [-C | -c] <commit> = like "squash" but keep only the previous
#                    commit's log message, unless -C is used, in which case
#                    keep only this commit's message; -c is same as -C but
#                    opens the editor
# x, exec <command> = run command (the rest of the line) using shell
# b, break = stop here (continue rebase later with 'git rebase --continue')
# d, drop <commit> = remove commit
# l, label <label> = label current HEAD with a name
# t, reset <label> = reset HEAD to a label
# m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
...

在这里你可以将提交前的单词从pick改为edit。在我们的情况下:

edit 376c762 Commit with wrong file

然后您保存文件并退出,如果您使用nano,则按Ctr + XYEnter

然后您将回到命令行,就在提交后。您可以执行以下操作来撤销上一次提交。文件和您将拥有未提交的更改。提示将显示当前提交哈希的前7个字符。

git restore HEAD^

接着你可以从提交中删除/添加/更改文件,添加并提交这个变更。然后为了继续rebase操作,你需要进行如下命令:

get rebase --continue 

如果在以后的提交中更改了相同的文件,则可能会出现冲突,您必须在继续之前解决并提交--continue。当重新定位完成时,您将会得到


0

您可以通过将空的本地分支推送到远程分支来删除远程分支中的所有文件 -

假设您想要删除origin的分支trial,那么您需要执行git push origin :trial


0

请确保您实际上已经删除了这些文件

rm -rf directory-to-remove/

然后从 Git 中删除:

git rm -r --cached directory-to-remove/

最后提交并推送:

git commit -a -m "Deleted files"
git push origin master

假设您当前的分支是主分支。

1
这是一个WordPress网站的图像。实际上,我并不想删除目录,但是我没有必要将2GB的图像推送到Bitbucket。 - nicoX
然后您应该在那些目录中添加.gitignore文件,并将其添加到git中。文件的内容可以是 *。git add directory/.gitignore - Gerharbo
我随后将它们包含在.gitignore中。 - nicoX
1
你可以在特定目录的.gitignore文件中添加“*”来排除该目录下的所有文件。首先从缓存中删除 git rm -rf --cached directory-to-remove/确保你添加了 .gitignore 文件 git add directory/.gitignore你可以使用 git status 检查哪些文件已准备提交。 - Gerharbo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接