SLIGHTNING 的编程日记

Windows 系统上的 Git 文件名大小写问题

现象

Git 默认是大小写不敏感的,这意味着单纯地更改文件的大小写是不能被检测到的。

例如:假如有一个文件原本在文件夹 menu 中,现将 menu 文件夹重命名为 Menu,Git 默认不能检测到这一更改。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
PS D:\test> git status
On branch main

No commits yet

Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: src/components/menu/.gitkeep

PS D:\test> Rename-Item src/components/menu Menu
PS D:\test> git status
On branch main

No commits yet

Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: src/components/menu/.gitkeep

要让 Git 检测文件名大小写的变化,需要设置 Git 大小写敏感。

设置 Git 设置文件名大小写敏感

在工作区中执行命令:

1
git config core.ignorecase false

或设置全局大小写敏感:

1
git config --global core.ignorecase false

设置完之后,Git 就能够检测到重命名后的文件了。

1
2
3
4
5
6
7
8
9
10
11
12
13
PS D:\test> git status
On branch main

No commits yet

Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: src/components/menu/.gitkeep

Untracked files:
(use "git add <file>..." to include in what will be committed)
src/components/Menu/

但是,此时 Git 并没有检测到重命名之前的文件已经不存在了。在上面的 git status 的输出中,可以看到 Git 没有检测到 src/components/menu/.gitkeep 被删除。在执行 git add . 后,重命名前的文件记录也不会被 Git 删除。

1
2
3
4
5
6
7
8
9
10
11
PS D:\test> git add .
PS D:\test> git status
On branch main

No commits yet

Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: src/components/Menu/.gitkeep
new file: src/components/menu/.gitkeep

尽管有些方法可以暂时解决这一问题(参见参考资料 1),但是这些方法太过麻烦。

Git 之所以识别不到重命名前的文件已被删除,是因为 Windows 默认不区分文件文件名的大小写,所以,只要将 Windows 文件路径设置为大小写大小写敏感,就可以彻底解决这一问题。

Windows 设置文件名大小写敏感

在 Windows 10 1803 或更高版本中,可以用 fsutil 命令对指定目录开启文件名大小写敏感(可能需要启用 WSL)。

使用管理员权限 PowerShell 运行:

1
fsutil file setCaseSensitiveInfo <路径> enable

执行完后,该路径下新建立的文件夹仍是大小写敏感的,但是原先已经存在的文件夹不会发生改变。

要使原先存在的文件夹也是大小写敏感的,可以递归设置:

1
Get-ChildItem <路径> -Recurse -Directory | % { fsutil file setCaseSensitiveInfo "$($_.FullName)" enable }

设置完后,Git 就能正常识别大小写了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
PS D:\test> git status
On branch main

No commits yet

Changes to be committed:
(use "git rm --cached <file>..." to unstage)
new file: src/components/Menu/.gitkeep
new file: src/components/menu/.gitkeep

Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
deleted: src/components/menu/.gitkeep

启用文件大小写敏感后会产生一些问题:

  • 位于 node_modules/.bin 目录中的命令可能无法识别,对该目录关闭大小写敏感即可。
  • VS Code 可能识别不到重命名后的文件,重启 VS Code 即可。

参考资料

  1. Git 文件名称大小写的天坑 - 掘金
  2. Windows 10 开启文件名大小写敏感功能 - 知乎
使用 Hexo 构建 | 主题 Lengux (有修改)| © 2026 SLIGHTNING