当前位置:   article > 正文

git将文件或目录添加进了.gitignore文件,为什么不生效?_gitignore文件不生效

gitignore文件不生效

如题,之所以将文件添加进了.gitignore文件但不生效,是因为该文件已经被add进git仓库了,已经被git托管了,这时git就没法ignore了。解决办法是先用git rm --cached将这些文件从git仓库中取消托管并提交,然后.gitignore文件才会生效。详细见如下描述。

已经添加到git仓库中的文件,如果在.gitignore中加入忽略,是不会生效的,因为他们已经添加到git仓库中了。

要先git rm --cached在git仓库中删除这些文件,然后再用git commit 提交这个删除操作。然后,.gitignore中对这些文件的忽略才会生效。

注意:git rm --cached只是让git不再托管这些文件,一定要加上--cached选项,如果不加,git不仅删除此文件的托管关系,还会从硬盘上删除此文件,可怕~~

例:

mokar@ubuntu:~/temp/555$ tree
.
├── aa
│   └── aa.c
└── bb
    └── bb.c
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

此例中,aa bb文件夹下两个文件都已经git add了:

mokar@ubuntu:~/temp/555$ git status
On branch master
nothing to commit, working directory clean
  • 1
  • 2
  • 3

此时编写.gitignore文件,将bb文件夹下的文件忽略掉,不会生效:

mokar@ubuntu:~/temp/555$ cat .gitignore
bb/
  • 1
  • 2

将ignore文件提交。
此时改动bb.c看看:

mokar@ubuntu:~/temp/555$ 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:   bb/bb.c
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

提示有改动,按理说,添加了ignore,应该不会提示的,但是因为我们把bb.c添加到git中了,所以git不会忽略bb.c的改动。
此时,我们用git rm --cached将bb.c从git中移除。
我们先要把bb.c的改动提交。然后再rm

mokar@ubuntu:~/temp/555$ ga   //git add .
mokar@ubuntu:~/temp/555$ gs   //git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   bb/bb.c

mokar@ubuntu:~/temp/555$ gcm    //git commit -m "sss"
[master 077628f] add bb.c
 1 file changed, 1 insertion(+)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

git rm --cached:

mokar@ubuntu:~/temp/555$ git rm --cached bb/bb.c
rm 'bb/bb.c'
mokar@ubuntu:~/temp/555$ gs
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        deleted:    bb/bb.c

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

此时提示bb/bb.c被删了。
我们再commit 一下:

mokar@ubuntu:~/temp/555$ git commit -m "ddd"
[master 0bac556] ddd
 1 file changed, 1 deletion(-)
 delete mode 100644 bb/bb.c
mokar@ubuntu:~/temp/555$ gs
On branch master
nothing to commit, working directory clean
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

然后我们再改一下bb/bb.c,就会发现不会再提示bb.c中有改动了。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/871316
推荐阅读
  

闽ICP备14008679号