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


当前回答

现在,苹果已经将所有MacOS用户更新为zsh,正确的答案不再有效。

git reset --soft HEAD^
zsh: no matches found: HEAD^

您可以通过单引号防止shell将^视为特殊字符。

git reset --soft 'HEAD^'

或者,您可以在shell中禁用此行为。通过更新~/.zshrc

unsetopt nomatch

其他回答

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 checkout origin/<remote-branch> <filename>
git commit --amend

我们可以采取的另一种方法是:

删除文件使用删除的文件进行新提交执行交互式重基并压缩两个提交推

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

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

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

    git checkout <commit_id> <path_to_file>

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

    git checkout origin/master <path_to_file>

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

将文件保存在本地(从gitcommit中删除)

如果要保留文件,可以使用--cached,如下所示:

git rm --cached filename

删除本地文件(并从gitcommit中删除)

否则,如果要删除文件,只需使用:

git rm filename