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


当前回答

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

其他回答

git reset --soft HEAD~1. 

这将撤消本地回购中的最后一次提交,并将所有内容移回提交前的阶段区域。然后,只需正常使用任何Git UI工具(如TortoiseGit、Git UI、Git Extensions…)来取消我们不想提交的文件的页面,然后再次提交。

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

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

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

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

$ git commit --amend // or stash and rebase to <commit_id> to amend changes

将文件保存在本地(从gitcommit中删除)

如果要保留文件,可以使用--cached,如下所示:

git rm --cached filename

删除本地文件(并从gitcommit中删除)

否则,如果要删除文件,只需使用:

git rm filename

这是我从比特桶回购中删除文件的工作,我最初将文件推送到分支。

git checkout origin/develop <path-to-file>
git add <path-to-file>
git commit -m "Message"
git push