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


当前回答

执行以下命令序列:

//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 --hard @{u}

然后把东西复制回去。提交,推。

正如接受的答案所示,您可以通过重置整个提交来实现这一点。但这是一种相当严厉的做法。要做到这一点,一个更干净的方法是保留提交,只需从中删除更改的文件。

git reset HEAD^ -- path/to/file
git commit --amend --no-edit

git reset会将文件恢复为上次提交时的状态,并将其存储在索引中。工作目录中的文件未被触动。然后,gitcommit将提交并将索引压缩到当前提交中。

这基本上会获取上一次提交中的文件版本,并将其添加到当前提交中。这不会导致任何净更改,因此文件有效地从提交中删除。

如果您想保留提交(可能您已经花了一些时间编写了详细的提交消息,不想丢失它),并且您只想从提交中删除文件,而不是完全从存储库中删除文件:

git checkout origin/<remote-branch> <filename>
git commit --amend

执行以下命令序列:

//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'