如何从最新提交中删除文件?
当前回答
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,而无需记住更复杂的命令、提交消息或键入。
其他回答
目前的答案都不合理。听起来有足够的需求,应该提出一个真正的解决方案:https://github.com/git/git/blob/master/Documentation/SubmittingPatches
git--取消提交<文件名>
很好。我知道我们不想修改历史记录,但如果我是本地人,无意中添加了本地“黑客”文件,并希望将其从提交中删除,这将非常有用。
使用rm删除文件将删除它!
您总是在git中添加提交,而不是删除,因此在本例中,将文件返回到第一次提交之前的状态(如果文件是新的,这可能是删除“rm”操作),然后重新提交,文件将继续。
要将文件恢复到以前的状态,请执行以下操作:
git checkout <commit_id> <path_to_file>
或者将其返回到远程HEAD的状态:
git checkout origin/master <path_to_file>
然后修改提交,您应该会发现文件已从列表中消失(并且没有从磁盘中删除!)
执行以下命令序列:
//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'
如果要从以前的提交中删除文件,请使用筛选器
git filter-branch --prune-empty --index-filter 'git rm --ignore-unmatch --cached "file_to_be_removed.dmg"'
如果看到此错误:
无法创建新备份。refs/original中已存在以前的备份/强制使用-f覆盖备份
只需删除本地存储库上的refs备份
$ rm -rf .git/refs/original/refs
我认为这里的其他答案是错误的,因为这是一个将错误提交的文件从上一次提交移回临时区域的问题,而不取消对它们所做的更改。这可以像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添加?
- 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之间的区别