全局 Git 忽略 macOS 系统文件

在任何 Mac 设备上执行以下步骤,让所有 Git 仓库自动忽略 .DS_Store 等系统文件,无需每个项目单独配置。
步骤一:创建全局忽略规则文件¶
打开终端,执行以下命令,在主目录下生成 ~/.gitignore_global:
cat > ~/.gitignore_global <<'EOF'
# macOS system files
.DS_Store
.DS_Store?
._*
.AppleDouble
.LSOverride
.Spotlight-V100
.Trashes
.fseventsd
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
EOF步骤二:告诉 Git 使用这个全局配置¶
git config --global core.excludesfile ~/.gitignore_global步骤三:验证配置是否生效¶
git config --global core.excludesfile输出 ~/.gitignore_global 即表示配置成功。
步骤四(按需):清理已有仓库中被追踪的文件¶
全局 gitignore 只阻止未来的追踪。若某个仓库里已有被提交的 .DS_Store,需额外清理:
# 查看哪些 .DS_Store 已被追踪
git ls-files | grep .DS_Store
# 从索引中移除(文件仍保留在磁盘)
git rm --cached $(git ls-files | grep .DS_Store)
# 提交这次清理
git commit -m "Remove tracked .DS_Store files"注意:若第一条命令没有输出,说明该仓库干净,无需执行后两步。
完成后,全局配置写入 ~/.gitconfig,对这台 Mac 上所有仓库永久生效。新建仓库无需任何额外操作。