如何清除 Git 仓库中的 .DS_Store 文件
清除已提交的 .DS_Store:find . -name .DS_Store 配合 git rm --cached 移出索引并提交;然后加入 .gitignore,最好配置全局忽略 git config --global core.excludesFile 防止再次混入。
.DS_Store 是 macOS Finder 生成的目录元数据文件,不该进版本库。 清理分两步:① 把已跟踪的 .DS_Store 移出索引;② 配置忽略规则防止再犯。
清理已提交的文件
# 找出并移出索引(本地文件保留)
find . -name ".DS_Store" -print0 | xargs -0 git rm --cached --ignore-unmatch
git commit -m "移除 .DS_Store"
git push
防止再犯
项目级(写进仓库):
echo ".DS_Store" >> .gitignore
git add .gitignore && git commit -m "忽略 .DS_Store"
全局级(推荐,所有仓库生效):
echo ".DS_Store" >> ~/.gitignore_global
git config --global core.excludesFile ~/.gitignore_global
全局配置后,任何项目都不会再误提交它,也不用在每个项目的 .gitignore 里重复。
常见问题(FAQ)
Q:.DS_Store 里有什么?为什么不该提交?
记录 Finder 的窗口位置、图标排列等本机视图状态。它对其他协作者是垃圾,且频繁变动(每次打开目录都可能变),会造成无意义的 diff 和冲突。
Q:Windows/Linux 有对应物吗?
Windows 的 Thumbs.db、desktop.ini,Linux 桌面环境的 .directory。全局 gitignore 里一起加上。
Q:历史里的 .DS_Store 要清理吗?
一般不值得——它体积小,重写历史成本高。但如果是统一治理(比如用 filter-repo 清理仓库),顺手 --path-glob "*.DS_Store" --invert-paths 清掉也行。