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


当前回答

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

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

干杯

其他回答

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

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

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

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

git reset --soft 'HEAD^'

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

unsetopt nomatch

如果要从以前的提交中删除文件,请使用筛选器

git filter-branch --prune-empty --index-filter 'git rm --ignore-unmatch --cached "file_to_be_removed.dmg"'

如果看到此错误:

无法创建新备份。refs/original中已存在以前的备份/强制使用-f覆盖备份

只需删除本地存储库上的refs备份

$ rm -rf .git/refs/original/refs

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

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