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


当前回答

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

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

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

git reset --soft 'HEAD^'

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

unsetopt nomatch

其他回答

我将用例子向你解释。设A、B、C为3次连续提交。提交B包含一个不应提交的文件。

git log  # take A commit_id
git rebase -i "A_commit_ID" # do an interactive rebase
change commit to 'e' in rebase vim # means commit will be edited
git rm unwanted_file
git rebase --continue
git push --force-with-lease <branchName>    

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

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

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

git reset --soft 'HEAD^'

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

unsetopt nomatch

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

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

干杯

git checkout HEAD~ path/to/file
git commit --amend

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

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