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


当前回答

我将用例子向你解释。设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 reset --hard @{u}

然后把东西复制回去。提交,推。

现有的答案都是关于从上次提交中删除不需要的文件。

如果您想从旧提交(甚至推送)中删除不需要的文件,并且不想创建新提交,这是不必要的,因为执行以下操作:

使用查找您希望文件符合的提交;

git-log--图形--装饰--单行

使用签出提交

git checkout<commit_id><path_to_file>

如果要删除许多文件,可以多次执行此操作。

3.

gitcommit-am“删除不需要的文件”

4.

查找错误添加文件的提交的commit_id,让我们在这里说“35c23c2”

git rebase 35c23c2~1-i//注意:“~1”是必需的

此命令根据您的设置打开编辑器。默认值为vim。如果要更改全局git编辑器,请使用;

git-config--全局core.editor<editor_name>

5.

将最后一次提交(应该是“删除不需要的文件”)移动到错误提交的下一行(在我们的例子中是“35c23c2”),并将命令设置为fixup:

pick 35c23c2 the first commit
fixup 0d78b28 remove unwanted files

保存文件后你应该很好。

6.

要完成:

git push-f

如果不幸发生冲突,则必须手动解决。

如果你不再需要那个文件,你可以

git rm file
git commit --amend
git push origin branch

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

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 reset--soft HEAD ^返回您的提交,当您键入git status时,它会告诉您要做什么:

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)