前言 有些时候,我们必须把某些文件放到Git工作目录中,但又不能提交它们,比如保存了数据库密码的配置文件、项目运行时生成的临时文件等等,每次git status
都会显示Untracked files ...
,让人不爽。
好在Git考虑到了大家的感受,在Git工作区的根目录下创建一个特殊的.gitignore
文件,然后把要忽略的文件名填进去,Git就会自动忽略这些文件。
gitignore规则 基本语法 以斜杠/
开头表示目录 以星号*
通配多个字符; 以问号?
通配单个字符 以方括号[]
包含单个字符的匹配列表 以叹号!
表示不忽略(跟踪)匹配到的文件或目录 示例 1 2 3 4 5 6 7 8 .DS_Store *.a !lib.a /TODO /target/ target/ doc/*.txt # 忽略文件如doc/ notes.txt,但是文件如doc/server/ arch.txt不忽略
push之后添加gitignore gitignore只能作用于 Untracked Files,如果某些文件(add和commit过的文件)已经被纳入了版本管理中,则修改gitignore是无效的。解决方法就是先把本地缓存删除(改变成Untracked状态),然后再提交。
1 2 3 4 5 git pull git rm - r git add . git commit - m 'update .gitignore' git push
如果是单个文件需要Untrack,git rm -r --cached .
建议改成git rm -r --cached path/filename
。
添加gitignore后pull错误 push之后添加了gitignore,也就是一部分的Tracked Files,现在不再Track。这时,其他用户在pull代码的时候,会出现错误: “The following untracked working tree files would be overwritten by merge”
解决办法:
1 2 3 git reset git clean -f -d git pull
自动生成gitignore 1、访问网址:gitignore.io
2、输入操作系统、IDE、编程语言等,就能自动生成通用的gitignore文件。
3、根据自己的实际需要,增删一些配置。
一个Demo 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 ### macOS ### # General .DS_Store .AppleDouble .LSOverride # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk ### End of macOS ### ### Intellij ### # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider # Reference: https: # General .idea/ # mpeltonen/sbt-idea plugin .idea_modules/ # File-based project format *.iws # IntelliJ out/ # CMake cmake-build-*/ # Crashlytics plugin (for Android Studio and IntelliJ) com_crashlytics_export_strings.xml crashlytics.properties crashlytics-build.properties fabric.properties ### End of Intellij ###
书签 A collection of useful .gitignore templates
Github使用.gitignore文件忽略不必要上传的文件
Git忽略规则
忽略特殊文件
解决Git在添加ignore文件之前就提交了项目无法再过滤问题