在 Git 中彻底消除 .DS_Store 文件

Posted by abining on March 27, 2025

在 Git 中彻底消除 .DS_Store 文件

1. .DS_Store 文件的由来

1.1 macOS 文件管理的历史

.DS_Store(Desktop Services Store)文件起源于 macOS 早期的 Finder(文件管理器)系统。早在 Mac OS X 10.0(Cheetah)时代,苹果公司为了改进用户体验,引入了 .DS_Store 文件来存储文件夹的自定义属性,例如图标排列方式、窗口大小、背景颜色等。

事实上,每当 macOS 用户打开一个新文件夹时,系统会自动生成 .DS_Store 文件,以便在下次访问该文件夹时保持一致的视觉布局。

1.2 什么时候生成 .DS_Store?

每当你在 Finder 中打开一个新文件夹,并进行以下操作时,macOS 就会自动创建 .DS_Store 文件:

  • 调整文件排列方式(按名称、按类型、按大小等)
  • 改变文件夹窗口的大小或位置
  • 设置文件夹的背景颜色或图片
  • 修改文件的显示方式(图标、列表、列视图等)

例如我对下图进行按大小排序。

这时候就可以发现git识别到了新增的文件。

2. 如何从 Git 仓库中移除 .DS_Store?

2.1 从当前仓库中删除 .DS_Store

如果之前提交过这个文件,可以使用以下命令删除所有已提交的 .DS_Store 文件:

1
find . -name .DS_Store -print0 | xargs -0 git rm --cached

然后提交更改:

1
2
git commit -m "Remove .DS_Store files"
git push origin <branch>

然后把文件从暂存区里面移出

1
git restore doc2.txt

2.2 添加 .DS_Store 到 .gitignore

为了防止 .DS_Store 文件再次被提交,我们需要在 .gitignore 文件中添加以下规则:

1
2
3
4
echo '.DS_Store' >> .gitignore
git add .gitignore
git commit -m "Ignore .DS_Store"
git push origin <branch>

3. 配置全局 Git 忽略 .DS_Store

如果你希望所有 Git 仓库都忽略 .DS_Store 文件,可以进行全局配置:

1
2
echo '.DS_Store' >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global

这样 .DS_Store 将被全局忽略,无需每次在 .gitignore 文件中手动添加。

4. 结论

.DS_Store 文件虽然对 macOS 用户有用,但在 Git 项目中往往是无用甚至有害的。通过正确的删除、忽略和预防策略,可以避免 .DS_Store 对版本控制的干扰,提高 Git 仓库的整洁性。