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


当前回答

执行以下命令序列:

//to remove the last commit, but preserve changes  
git reset --soft HEAD~1

//to remove unneded file from the staging area  
git reset HEAD `<your file>` 

//finally make a new commit  
git commit -m 'Your message'

其他回答

我认为这里的其他答案是错误的,因为这是一个将错误提交的文件从上一次提交移回临时区域的问题,而不取消对它们所做的更改。这可以像Pariosh Singh建议的那样:

git reset --soft HEAD^ 

or

git reset --soft HEAD~1

然后重置不需要的文件,以便将它们从提交中删除(旧方法):

git reset HEAD path/to/unwanted_file

注意,自从Git 2.23.0以来,人们可以(以新的方式):

git restore --staged path/to/unwanted_file

现在再次提交,您甚至可以重复使用相同的提交消息:

git commit -c ORIG_HEAD  

如果出于任何原因(就像我的情况一样),您在重新设置上次提交的所有文件时遇到困难,如git reset--soft HEAD^,并且您的情况满足以下条件,您可以按照我下面的解释进行操作。

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

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

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

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

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

$ git commit --amend // or stash and rebase to <commit_id> to amend changes
git checkout HEAD~ path/to/file
git commit --amend

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

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

干杯