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


当前回答

如果您正在使用GitHub,但尚未提交,GitHub Desktop可以轻松解决此问题:

选择存储库->撤消最近提交取消选择错误添加的文件。您的上一条提交消息将已经出现在对话框中。按下提交按钮!

其他回答

如果你不再需要那个文件,你可以

git rm file
git commit --amend
git push origin branch

我只想补充上面的答案,因为我必须运行一个额外的命令:

git reset --soft HEAD^
git checkout origin/master <filepath>

干杯

我将当前文件复制到另一个文件夹中,然后通过以下方式删除所有未推送的更改:

git reset --hard @{u}

然后把东西复制回去。提交,推。

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

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

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

git reset --soft 'HEAD^'

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

unsetopt nomatch
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,而无需记住更复杂的命令、提交消息或键入。