我使用命令错误地将文件添加到 Git :

git add myfile.txt

我还没有执行 git 承诺 。 我如何撤销此操作, 使这些更改不被包含在承诺中 ?


当前回答

要撤销 git 添加, 请使用 :

git reset filename

其他回答

根据许多其他答案, 您可以使用 Git 重置

不过:

我找到了这个大小文章, 实际添加了 Git 命令(别名) , 用于 git unadd : 详情请见 git unadd 或 。

简而言之

git config --global alias.unadd "reset HEAD"

现在你可以

git unadd foo.txt bar.txt

或/直接:

git reset HEAD foo.txt bar.txt

您想要 :

git rm --cached <added_file_to_undo>

理由:

当我刚开始做这个的时候,我第一次尝试

git reset .

(取消我最初添加的全部内容), 只是为了得到这个(不是这样的)有用信息:

fatal: Failed to resolve 'HEAD' as a valid ref.

结果发现,这是因为 HEAD ref (blanch?) 直到第一次承诺之后才存在。 这就是说,你会遇到跟我一样的初学者的问题, 如果你的工作流程像我的一样, 像是:

cd to my great new project directory to try out Git, the new hotness git init git add . git status ... lots of crap scrolls by ... => Damn, I didn't want to add all of that. google "undo git add" => find Stack Overflow - yay git reset . => fatal: Failed to resolve 'HEAD' as a valid ref.

邮件列表上记录了一个窃听器 记录了这个无益之处

正确的解决方案就在 Git 状态输出中( 是的, 我将它伪装成“ 废话 ” ) 。

... # 将要执行的修改 : # (使用“ git rm -- cashed < file >...” 来取消)...

事实上,解决办法是使用Git rm -- cashed FILE。

在此注意其它处的警告 - git rm 删除您本地的文件工作副本, 但如果您使用 -- cashed , 则不使用。 这是 Git help rm 的结果 :

--cached 使用此选项来卸载和从索引中删除路径。 工作树文件, 不论是否修改, 都会被左移 。

我开始使用

git rm --cached .

以删除所有内容并重新开始。 虽然没有成功, 因为添加. 是循环的, 结果显示 Rm 需要 - r 循环。 叹息 。

git rm -r --cached .

好了,我现在回到我开始的地方。下次我要用...

git add -n .

我把所有东西都拉到一个安全的地方,

请注意,如果您没有指定修改,则必须包含一个分隔符。例如,我的控制台:

git reset <path_to_file>
fatal: ambiguous argument '<path_to_file>': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

git reset -- <path_to_file>
Unstaged changes after reset:
M    <path_to_file>

(1.7.5.4版总版)

如上文所述,从中转区删除新文件(仅在出现新文件的情况下):

git rm --cached FILE

使用 rm -- -- 刻录仅用于新文件不小心添加 。

git rm --cached . -r

将“ un- add- add” 添加您从当前目录中添加的所有内容递归到当前目录