为何.git/info/exclude仅对项目根目录文件生效,子目录不生效?
Git排除规则问题:.git/info/exclude无法排除子目录下的同名文件
当前项目中,.git/info/exclude只能排除根目录下的test.txt,子目录里的同名文件无法被排除,但其他项目无此问题。使用Git版本为git version 2.34.1。
问题复现步骤
# 创建根目录下的test.txt $ echo "test" > test.txt # 检测到未跟踪文件 $ git status On branch main Untracked files: (use "git add <file>..." to include in what will be committed) test.txt nothing added to commit but untracked files present (use "git add" to track) # 将test.txt加入.git/info/exclude $ echo "test.txt" >> .git/info/exclude # 根目录文件已被排除,工作树干净 $ git status On branch main nothing to commit, working tree clean # 在子目录创建同名文件 $ echo "test" > my-project/src/main/resources/test.txt # 子目录下的test.txt仍显示为未跟踪 $ git status On branch main Untracked files: (use "git add <file>..." to include in what will be committed) my-project/src/main/resources/test.txt nothing added to commit but untracked files present (use "git add" to track)
相关文件内容
.git/info/exclude
$ cat -et .git/info/exclude # git ls-files --others --exclude-from=.git/info/exclude$ # Lines that start with '#' are comments.$ # For a project mostly in C, the following would be a good set of$ # exclude patterns (uncomment them if you want to use them):$ # *.[oa]$ # *~$ test.txt$
.gitignore
$ cat -et .gitignore **/target/**$ !**/src/**$ .metadata$ .settings$ .classpath$ .project$ .idea$ *.iml$
问题原因及解决办法
核心原因
- 默认的
test.txt规则仅匹配当前目录下的文件,不递归子目录; .gitignore中的!**/src/**是强制包含规则,优先级高于排除规则,会让src目录下所有文件(包括test.txt)不受.git/info/exclude约束。
解决方法
方法一:修改.git/info/exclude的递归规则
把test.txt改成**/test.txt,这样就能匹配任意层级的test.txt:
# 替换原规则(Linux/macOS) sed -i 's/test.txt/**\/test.txt/g' .git/info/exclude
Windows环境直接打开.git/info/exclude文件手动修改即可。
方法二:调整.gitignore规则
如果必须保留!**/src/**,就在.gitignore末尾补充排除规则,覆盖强制包含:
echo "**/test.txt" >> .gitignore
这样所有层级的test.txt都会被排除,不受src目录的强制包含影响。
内容的提问来源于stack exchange,提问作者ka3ak
相关产品推荐
相关产品推荐

