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


当前回答

git rm  -r ./* --cached

这将删除所有缓存/暂存文件

其他回答

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~1

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

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

git reset --soft HEAD~1. 

这将撤消本地回购中的最后一次提交,并将所有内容移回提交前的阶段区域。然后,只需正常使用任何Git UI工具(如TortoiseGit、Git UI、Git Extensions…)来取消我们不想提交的文件的页面,然后再次提交。

一些对我有用的东西,但仍然认为应该有更好的解决方案:

$ git revert <commit_id>
$ git reset HEAD~1 --hard

只需将要放弃的更改保留在另一个提交中,检查其他人

$ git commit --amend // or stash and rebase to <commit_id> to amend changes

执行以下命令序列:

//to remove the last commit, but preserve changes  
git reset --soft HEAD~1

//to remove unneded file from the staging area  
git reset HEAD `<your file>` 

//finally make a new commit  
git commit -m 'Your message'