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


当前回答

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 checkout origin/<remote-branch> <filename>
git commit --amend

使用gitGUI可以简化从先前提交中删除文件的过程。

假设这不是一个共享分支,并且您不介意重写历史,那么运行:

git gui citool --amend

您可以取消检查错误提交的文件,然后单击“提交”。

该文件将从提交中删除,但将保留在磁盘上。因此,如果在错误添加文件后取消选中该文件,它将显示在未跟踪文件列表中(如果在错误修改文件后取消检查该文件,则会显示在未提交的更改列表中)。

git reset--soft HEAD ^返回您的提交,当您键入git status时,它会告诉您要做什么:

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
Here is the step to remove files from Git Commit.

>git reset --soft HEAD^1(either commitid ) -- now files moved to the staging area.
>git rm --cached filename(it will removed the file from staging area)
>git commit -m 'meaningfull message'(Now commit the required files)

你可以简单地尝试一下。

git reset --soft HEAD~1

并创建新的提交。

然而,有一个很棒的软件“gitkraken”。这使得使用git很容易。