这是一种思考方式:
git rm --cached [file]
这只是从跟踪中删除文件(文件添加后的状态 - 即 git add [file])
git reset HEAD [file]
这只是继续跟踪对文件的更改,但会将其放回“未暂存”区域。
这是一个例子。
首先,我创建了 4 个未跟踪的文件:
$ for i in {A..D}; do touch $i; echo "First line" > $i; done
$ ls
A B C D
$ git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
A
B
C
D
nothing added to commit but untracked files present (use "git add" to track)
接下来,我使用 git add 跟踪它们,然后我将提交更改:
$ git add .
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: A
new file: B
new file: C
new file: D
$ git commit -m "First Commit"
[master 6e8d625] First Commit
4 files changed, 4 insertions(+)
create mode 100644 A
create mode 100644 B
create mode 100644 C
create mode 100644 D
$ git status
On branch master
nothing to commit, working directory clean
现在我将修改文件 A 以便 git 获取更改,然后将更改的文件添加到暂存区域:
$ echo "First line of file A" > A
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: A
no changes added to commit (use "git add" and/or "git commit -a")
$ git add A
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
modified: A
现在这就是差异重要的地方。
我要给你的第一个例子是当你使用git rm --cached时会发生什么:
$ git rm --cached A
rm 'A'
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
deleted: A
Untracked files:
(use "git add <file>..." to include in what will be committed)
A
注意文件 A 现在是如何未被跟踪的,就像一开始将它添加到 git 之前的样子(当使用“ git add . ”时)。
现在,第二个例子是如果我使用git reset HEAD代替:
$ git reset HEAD A
Unstaged changes after reset:
M A
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: A
no changes added to commit (use "git add" and/or "git commit -a")
在这里您会注意到它将文件 A 的状态重置为未暂存状态,但仍继续跟踪它的更改。