如何从最新提交中删除文件?


当前回答

现在,苹果已经将所有MacOS用户更新为zsh,正确的答案不再有效。

git reset --soft HEAD^
zsh: no matches found: HEAD^

您可以通过单引号防止shell将^视为特殊字符。

git reset --soft 'HEAD^'

或者,您可以在shell中禁用此行为。通过更新~/.zshrc

unsetopt nomatch

其他回答

从git 2.23开始,您可以简单地使用以下命令:

git restore --staged <file>
git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "removed unwanted file from git"

将仍然保留本地文件。如果您也不希望文件在本地,可以跳过--cached选项。

如果所有工作都在您的本地分支上,您需要在以后提交时保存该文件,就像拥有一个干净的历史记录一样,我认为一个更简单的方法是:

git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit --squash <commit_id>
git add <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "brand new file!"
git rebase --interactive <commit_id>^

然后,您就可以轻松地完成rebase,而无需记住更复杂的命令、提交消息或键入。

如果要从以前的提交中删除文件,请使用筛选器

git filter-branch --prune-empty --index-filter 'git rm --ignore-unmatch --cached "file_to_be_removed.dmg"'

如果看到此错误:

无法创建新备份。refs/original中已存在以前的备份/强制使用-f覆盖备份

只需删除本地存储库上的refs备份

$ rm -rf .git/refs/original/refs

注意!如果您只想从上一次提交中删除一个文件,并将其保存在磁盘上,请阅读上面juzzlin的回答。

如果这是您最后一次提交,并且您希望从本地和远程存储库中完全删除该文件,您可以:

删除文件git-rm<file>带有修正标志的commit:gitcommit--修正

修正标志告诉git再次提交,但“合并”(不是合并两个分支的意思)这次提交与最后一次提交。

如注释中所述,在这里使用gitrm就像使用rm命令本身一样!

我们可以采取的另一种方法是:

删除文件使用删除的文件进行新提交执行交互式重基并压缩两个提交推