在 Git 中忽略文件,主要通过 .gitignore 文件 来实现。下面从基础到常见场景给你说明。
.gitignore 文件touch .gitignore
# 忽略所有 .log 文件
*.log
# 忽略 node_modules 目录
node_modules/
# 忽略 build 目录
build/
# 忽略某个具体文件
config.local.js
| 规则 | 说明 |
|---|---|
*.txt |
忽略所有 txt 文件 |
dir/ |
忽略 dir 目录及其内容 |
/dir |
只忽略根目录下的 dir |
!a.txt |
不忽略 a.txt(例外) |
*.log + !important.log |
忽略日志但保留 important.log |
示例:
*.log
!debug.log
如果文件已经被 Git 跟踪,.gitignore 不会生效,需要先移除:
git rm --cached 文件名
例如:
git rm --cached config.local.js
然后提交:
git commit -m "stop tracking config.local.js"
git config --global core.excludesfile ~/.gitignore_global
在 ~/.gitignore_global 中写规则,比如:
.DS_Store
*.swp
git check-ignore 文件名
如果输出文件名,说明被忽略了。
.gitignore 示例target/
*.class
__pycache__/
*.pyc
venv/
node_modules/
dist/
.env
如果你有 具体语言或框架(如 Vue、Spring、Go),我可以帮你直接写一份合适的 .gitignore。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。