假设我们有一个文件无意中添加到我们的存储库中:
stackoverflow$ echo this file is important > junkfile
stackoverflow$ git add junkfile
stackoverflow$ git ci -m 'added a file'
在某些时候,我们意识到该文件并不重要,因此我们将其添加到我们的.gitignore
文件中:
stackoverflow$ echo junkfile >> .gitignore
stackoverflow$ git ci -m 'ignore junkfile' .gitignore
稍后,我们对该文件进行一些更改:
stackoverflow$ sed -i 's/ is / is not/' junkfile
当然,即使文件列在 中.gitignore
,我们已经告诉 git 我们要跟踪它,所以git status
显示:
stackoverflow$ 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: junkfile
#
no changes added to commit (use "git add" and/or "git commit -a")
我们需要从存储库中删除该文件(不从我们的工作树中删除该文件)。我们可以使用以下--cached
标志来做到这一点git rm
:
stackoverflow$ git rm --cached junkfile
rm 'junkfile'
这阶段delete
操作...
stackoverflow$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: junkfile
#
...所以我们需要提交它:
stackoverflow$ git commit -m 'removed junkfile from repository'
[master 19f082a] removed junkfile from repository
1 file changed, 1 deletion(-)
delete mode 100644 junkfile
现在如果我们运行git status
git 会忽略这个文件:
stackoverflow$ git status
# On branch master
nothing to commit, working directory clean
即使它仍然在我们的工作树中:
stackoverflow$ cat junkfile
this file is not important