关于git:如何忽略已经提交的文件?

How to ignore a file which is already committed?

以前,以下是我的.gitignore文件:

1
2
3
...
config/database.yml
.DS_Store

后来我在config目录中创建了一个app_config.yml文件并提交了它。

现在,我意识到我不需要git存储库中的app_config.yml文件。
然后我修改了.gitignore文件:

1
2
3
4
...
config/app_config.yml
config/database.yml
.DS_Store

现在,当我提交时,该app_config.yml文件仍在我的存储库中。
我想从我的仓库中删除该文件。 我该怎么做?


如"忽略不会删除文件"中所述
(以下引用了Nick Quaranto的精彩文章,
在他的博客git ready中"一次学习git一遍提交"):

When you tell Git to ignore files, it’s going to only stop watching changes for that file, and nothing else.
This means that the history will still remember the file and have it.

If you want to remove a file from the repository, but keep it in your working directory, simply use:

1
git rm --cached <file>

However, this will still keep the file in history.

If you actually want to remove it from history, you really have two options:

  • rewrite your repository’s commits, or
  • start over.

Both options really suck, and that’s for a good reason: Git tries hard not to lose your data.
Just like with rebasing, Git forces you to think about these kinds of options since they are destructive operations.

If you did actually want to remove a file from history, git filter-branch is the hacksaw you’re looking for.
Definitely read up on its manpage before using it, since it will literally rewrite your project’s commits. This actually is a great tool for some actions, and can do all sorts of stuff like totally removing an author’s commits to moving the project root folder around. The command to remove a file from all revisions is:

1
git filter-branch --index-filter 'git rm --cached <file>' HEAD

This action can definitely be useful when you need to blow out sensitive or confidential information that may have been placed in your repository


当您想开始忽略已提交的文件并将其保留在项目中时,这无济于事...因为git rm --cached将从git repo中删除它...

我发现了该如何阻止Git从此提交向前跟踪对文件的任何更改? 这是我一直在寻找的..

希望它对其他人也有用...