如何从最新提交中删除文件?
当前回答
git reset--soft HEAD ^返回您的提交,当您键入git status时,它会告诉您要做什么:
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
其他回答
我将用例子向你解释。设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 rm -r ./* --cached
这将删除所有缓存/暂存文件
git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "removed unwanted file from git"
将仍然保留本地文件。如果您也不希望文件在本地,可以跳过--cached选项。
如果所有工作都在您的本地分支上,您需要在以后提交时保存该文件,就像拥有一个干净的历史记录一样,我认为一个更简单的方法是:
git rm --cached <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit --squash <commit_id>
git add <file_to_remove_from_commit_<commit_id>_which_added_file>
git commit -m "brand new file!"
git rebase --interactive <commit_id>^
然后,您就可以轻松地完成rebase,而无需记住更复杂的命令、提交消息或键入。
从git 2.23开始,您可以简单地使用以下命令:
git restore --staged <file>
如果尚未在服务器上推送更改,则可以使用
git reset --soft HEAD~1
它将重置所有更改并恢复为一次提交
如果您已经推动了更改,请按照@CharlesB回答的步骤操作
推荐文章
- 为什么我需要显式地推一个新分支?
- 如何撤消最后的git添加?
- Rubymine:如何让Git忽略Rubymine创建的.idea文件
- Gitignore二进制文件,没有扩展名
- Git隐藏错误:Git隐藏弹出并最终与合并冲突
- 了解Git和GitHub的基础知识
- 没有。Git目录的Git克隆
- Git与Mercurial仓库的互操作性
- 忽略git中修改(但未提交)的文件?
- “git restore”命令是什么?“git restore”和“git reset”之间有什么区别?
- Git合并与强制覆盖
- Git拉另一个分支
- 在Bash命令提示符上添加git分支
- 如何更改Git日志日期格式
- git pull -rebase和git pull -ff-only之间的区别