这个问题可以有两种理解,两种情况下的最佳答案是不同的。
Question 1: I added a previously untracked file to the staging area. How can I remove this file from the staging area without removing it from the file system?
Answer 1: Use the following command, as described in John Feminella's answer:
git rm --cached <file>
Question 2: I modified a file already tracked, and added my modifications to the staging area. How can I remove my modifications from the staging area? I.e., how can I unstage my modifications in the file?
Answer 2: Use the following command, as described in David Underhill's answer:
git reset <file>
According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use
git commit -a -m "comment"
adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files.
If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but...
If you have done that already, you will need to use
Git restore --staged <file>
还有,请不要问我十年前在哪里……
我想念你,这个答案留给后人。
只使用git rm——cached [file]从索引中删除文件。
Git reset <filename>可以用来从索引中删除添加的文件,因为这些文件从未提交。
% git add First.txt
% git ls-files
First.txt
% git commit -m "First"
% git ls-files
First.txt
% git reset First.txt
% git ls-files
First.txt
注意:git reset First.txt在提交后对索引没有影响。
这就把我带到了git恢复的主题——staging <file>。它可以用于(假定在第一次提交之后)从索引中删除添加的文件,因为这些文件从未提交过。
% git add Second.txt
% git status
On branch master
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: Second.txt
% git ls-files
First.txt
Second.txt
% git restore --staged Second.txt
% git ls-files
First.txt
% git add Second.txt
% git commit -m "Second"
% git status
On branch master
nothing to commit, working tree clean
% git ls-files
First.txt
Second.txt
Desktop/Test% git restore --staged .
Desktop/Test% git ls-files
First.txt
Second.txt
Desktop/Test% git reset .
Desktop/Test% git ls-files
First.txt
Second.txt
% git rm --cached -r .
rm 'First.txt'
rm 'Second.txt'
% git ls-files
看最后15行。如果您不想与第一次提交、第二次提交、提交前、提交后混淆....总是使用git rm——cached [file]