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


当前回答

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

其他回答

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

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

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

$ git commit --amend // or stash and rebase to <commit_id> to amend changes
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^,并且您的情况满足以下条件,您可以按照我下面的解释进行操作。

您试图删除的文件在上次提交之前已存在于存储库中您可以撤消自上次提交以来文件中的所有更改(HEAD~2-上次提交之前的提交)

然后,您可以撤消自上一次提交(HEAD~2)以来的所有更改,保存文件,将其暂存(git-add文件名),然后运行gitcommit--modify--no edit。这将提交“新的更改”,这实际上是将文件重新提交到上次提交之前的最后一次提交。

最好的方法是使用SourceTree(也可以根据需要从命令行执行),并且:

检查新分支机构(出于安全原因)然后在要更改的提交之前使用gitreset-soft进行提交它将允许您删除(暂存/取消暂存)不需要的文件:)

如果您正在使用GitHub,但尚未提交,GitHub Desktop可以轻松解决此问题:

选择存储库->撤消最近提交取消选择错误添加的文件。您的上一条提交消息将已经出现在对话框中。按下提交按钮!