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


当前回答

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

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

其他回答

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,而无需记住更复杂的命令、提交消息或键入。

Here is the step to remove files from Git Commit.

>git reset --soft HEAD^1(either commitid ) -- now files moved to the staging area.
>git rm --cached filename(it will removed the file from staging area)
>git commit -m 'meaningfull message'(Now commit the required files)

如果要从以前的提交中删除文件,请使用筛选器

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

如果你还没有将你的更改推送到git

git reset --soft HEAD~1

它将重置所有更改并恢复为一次提交

如果这是您最后一次提交,并且您希望从本地和远程存储库中删除文件,请尝试以下操作:

git rm <file>
 git commit --amend

甚至更好:

先重置

git reset --soft HEAD~1

重置不需要的文件

git reset HEAD path/to/unwanted_file

再次提交

git commit -c ORIG_HEAD  

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

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

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

    git checkout <commit_id> <path_to_file>

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

    git checkout origin/master <path_to_file>

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