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


当前回答

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

其他回答

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

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

使用rm删除文件将删除它!

您总是在git中添加提交,而不是删除,因此在本例中,将文件返回到第一次提交之前的状态(如果文件是新的,这可能是删除“rm”操作),然后重新提交,文件将继续。

要将文件恢复到以前的状态,请执行以下操作:

    git checkout <commit_id> <path_to_file>

或者将其返回到远程HEAD的状态:

    git checkout origin/master <path_to_file>

然后修改提交,您应该会发现文件已从列表中消失(并且没有从磁盘中删除!)

如果你不再需要那个文件,你可以

git rm file
git commit --amend
git push origin branch

目前的答案都不合理。听起来有足够的需求,应该提出一个真正的解决方案:https://github.com/git/git/blob/master/Documentation/SubmittingPatches

git--取消提交<文件名>

很好。我知道我们不想修改历史记录,但如果我是本地人,无意中添加了本地“黑客”文件,并希望将其从提交中删除,这将非常有用。

我将用例子向你解释。设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>