Git 忽略特定文件的方法
1. 假设文件未被跟踪(未 add 过)
如果文件还没有被 git add 添加到版本控制,可以直接将它加入 .gitignore:
shell
echo "文件名" >> .gitignore2. 假设文件已被跟踪(已 commit 过)
如果文件已经被 Git 跟踪,.gitignore 对它无效。需要告诉 Git 忽略对该文件的后续修改:
shell
git update-index --assume-unchanged <文件路径>恢复跟踪:
shell
git update-index --no-assume-unchanged <文件路径>3. 跳过工作树(更安全的方式)
shell
git update-index --skip-worktree <文件路径>恢复:
shell
git update-index --no-skip-worktree <文件路径>--assume-unchanged vs --skip-worktree 的区别
| 特性 | assume-unchanged | skip-worktree |
|---|---|---|
| 用途 | 性能优化,假设文件不会改变 | 明确告诉 Git 忽略本地修改 |
| 安全性 | 较低(pull 时可能被覆盖) | 较高(pull 时不会覆盖) |
| 推荐场景 | 临时忽略大文件改动 | 永久性忽略配置文件改动 |
4. 查看当前被忽略的文件
shell
git ls-files -v | grep '^[hsS]'- h 表示 --assume-unchanged
- S 表示 --skip-worktree
示例
shell
# 忽略 config/local.yaml 的本地修改
git update-index --skip-worktree config/local.yaml
# 恢复跟踪
git update-index --no-skip-worktree config/local.yaml