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


当前回答

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

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

其他回答

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 2.23开始,您可以简单地使用以下命令:

git restore --staged <file>

使用rm删除文件将删除它!

您总是在git中添加提交,而不是删除,因此在本例中,将文件返回到第一次提交之前的状态(如果文件是新的,这可能是删除“rm”操作),然后重新提交,文件将继续。

要将文件恢复到以前的状态,请执行以下操作:

    git checkout <commit_id> <path_to_file>

或者将其返回到远程HEAD的状态:

    git checkout origin/master <path_to_file>

然后修改提交,您应该会发现文件已从列表中消失(并且没有从磁盘中删除!)

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

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

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

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

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

git reset --soft 'HEAD^'

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

unsetopt nomatch