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


当前回答

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)

其他回答

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)

执行以下命令序列:

//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'

注意!如果您只想从上一次提交中删除一个文件,并将其保存在磁盘上,请阅读上面juzzlin的回答。

如果这是您最后一次提交,并且您希望从本地和远程存储库中完全删除该文件,您可以:

删除文件git-rm<file>带有修正标志的commit:gitcommit--修正

修正标志告诉git再次提交,但“合并”(不是合并两个分支的意思)这次提交与最后一次提交。

如注释中所述,在这里使用gitrm就像使用rm命令本身一样!

正如接受的答案所示,您可以通过重置整个提交来实现这一点。但这是一种相当严厉的做法。要做到这一点,一个更干净的方法是保留提交,只需从中删除更改的文件。

git reset HEAD^ -- path/to/file
git commit --amend --no-edit

git reset会将文件恢复为上次提交时的状态,并将其存储在索引中。工作目录中的文件未被触动。然后,gitcommit将提交并将索引压缩到当前提交中。

这基本上会获取上一次提交中的文件版本,并将其添加到当前提交中。这不会导致任何净更改,因此文件有效地从提交中删除。

git rm  -r ./* --cached

这将删除所有缓存/暂存文件