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


当前回答

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 reset --soft HEAD^
git checkout origin/master <filepath>

干杯

如果尚未在服务器上推送更改,则可以使用

git reset --soft HEAD~1

它将重置所有更改并恢复为一次提交

如果您已经推动了更改,请按照@CharlesB回答的步骤操作

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

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

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

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

我认为这里的其他答案是错误的,因为这是一个将错误提交的文件从上一次提交移回临时区域的问题,而不取消对它们所做的更改。这可以像Pariosh Singh建议的那样:

git reset --soft HEAD^ 

or

git reset --soft HEAD~1

然后重置不需要的文件,以便将它们从提交中删除(旧方法):

git reset HEAD path/to/unwanted_file

注意,自从Git 2.23.0以来,人们可以(以新的方式):

git restore --staged path/to/unwanted_file

现在再次提交,您甚至可以重复使用相同的提交消息:

git commit -c ORIG_HEAD