从GIT控制中移除一个文件

67

可能是重复问题:
git - 从源代码控制中移除文件(但不从源代码中移除)

我有一个当前存在于GIT仓库中的.classpath文件。

当我从远程仓库拉取时(git pull origin master),如何从GIT控制中删除此文件,我是指不删除计算机上的该文件,而是将其从GIT版本控制中移除。(因为这个文件不需要版本控制)。

P.S.

我尝试使用git rm <path-to>/.classpath,但随后整个项目都报错了,说明class path错误。为什么git rm会删除我的文件而不是从版本控制中移除它?

2个回答

137

使用 git rm --cached 从索引中移除,但不会从工作树中移除。

之后,您应该将 .classpath 添加到您的 .gitignore 文件中,以防止再次提交。


1
如何添加到 .gitignore 文件中,您可以具体说明一下吗? - Leem.fin
2
在您的目录顶部创建一个名为“.gitignore”的文件,并将.classpath放入其中。您还可以使用通配符来忽略与某个模式匹配的文件(例如,*.class以忽略所有已编译的Java类)。您可能还可以在子目录中进行.gitignores(然后仅适用于该项目的一部分),但我忘记了。请参见http://linux.die.net/man/5/gitignore。 - Platinum Azure
1
那我创建.gitignore文件然后把文件名写入该文件对吗? - Leem.fin
3
可以,对于像 .classpath 这样的单个文件,这将起作用。我还建议提交 .gitignore 文件,以便其他开发人员使用它,也不会意外地提交 .classpath 文件。 - Platinum Azure
1
我需要指定 .classpath 文件的完整路径吗?还是只需要无论在哪里放置文件名即可(当然,它必须在项目文件夹下)? - Leem.fin
显示剩余2条评论

18

为什么使用 git rm 命令会删除我的文件而不是从版本控制中移除?

因为这就是该命令所声明的操作。

$ git help rm
NAME
       git-rm - Remove files from the working tree and from the index

SYNOPSIS
       git rm [-f | --force] [-n] [-r] [--cached] [--ignore-unmatch] [--quiet]
       [--] <file>...

DESCRIPTION
       Remove files from the index, or from the working tree and the index.
       ... When --cached is given,
       the staged content has to match either the tip of the branch or the
       file on disk, allowing the file to be removed from just the index.

OPTIONS
      ...

       --cached
           Use this option to unstage and remove paths only from the index.
           Working tree files, whether modified or not, will be left alone.

正如Platinum Azure所说,使用git rm --cached只从源代码管理中删除它,并使用.gitignore来防止它出现并停止在git status中显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接