如何从上次提交中删除文件,但保留其他所有内容?请注意,我还没有将任何东西推送到远程存储库,所以我只需要在本地执行此操作。
我的工作流程:
- 编辑几个文件
- 不小心创建了一个名为
untitled.txt
- 提交一切
- 注意不需要的
untitled.txt
文件 - 删除它
- ???
- 从此过上幸福的生活
提前致谢!
如何从上次提交中删除文件,但保留其他所有内容?请注意,我还没有将任何东西推送到远程存储库,所以我只需要在本地执行此操作。
我的工作流程:
untitled.txt
untitled.txt
文件提前致谢!
为什么不让下一次提交删除文件?编辑提交历史记录通常被认为是不好的做法,并且在后续提交中删除文件并没有什么可耻的。
git rm untitled.txt
git commit -m "Woopsy"
The other answers are fine if you want to not only remove the file from the last commit, but completely.
But what if the creation of the file is not accidental, only the addition of that file to the commit?
If you want to just delete the file from the last commit, but keep the file in your working copy so that you can git add
it to another commit, you can add --cached
to the rm
command:
git rm --cached wanted-for-another-commit-but-not-this-one.txt
git commit -a --amend
Now verify that it's gone from the commit:
git show -p # no more diff between /dev/null and the file!
Verify it's still there:
ls -l wanted-for-another-commit-but-not-this-one.txt
Verify it's in the list of untracked files, eligible for a git add
:
git status
Basically what we have done is removed the file from the index of staged files, while keeping the working copy. The git commit -a --amend
command is aware not only of changes in the working copy, but in the index also. It notices a removal from the index and propagates that change to the newly rewritten commit.