Git忽略提交规则 .gitignore配置
封面图
•
2025-11-20
•
git
256
0
0
0
在使用 Git 进行版本控制时,`.gitignore` 文件用于告诉 Git 哪些文件或目录应该被忽略(即不加入版本控制)。以下是一些常见的 `.gitignore` 配置规则和示例: --- ## ✅ 一、基本结构 `.gitignore` 文件通常放在项目根目录下。每一行表示一个要忽略的模式。 ### 示例: ```gitignore # 忽略所有 .log 文件 *.log # 忽略整个 build 目录 /build/ # 忽略 node_modules 目录(适用于 Node.js 项目) node_modules/ # 忽略 Mac 系统生成的文件 .DS_Store ``` --- ## ✅ 二、常见忽略规则 ### 1. **操作系统相关** ```gitignore # macOS .DS_Store Icon? .AppleDouble .LSOverride # Windows Thumbs.db ehthumbs.db Desktop.ini # Linux *~ ``` ### 2. **开发工具相关** ```gitignore # VSCode .vscode/ # IntelliJ / Android Studio .idea/ *.iml *.ipr *.iws # Eclipse .classpath .project .settings/ # Sublime Text *.sublime-project *.sublime-workspace # Vim *.swp *.swo *.swn ``` ### 3. **编译产物** ```gitignore # Java *.class *.jar *.war *.ear /target/ # Python __pycache__/ *.pyc *.pyo *.pyd env/ venv/ # Node.js node_modules/ npm-debug.log package-lock.json # Ruby .bundle Gemfile.lock vendor/ # Go bin/ pkg/ ``` ### 4. **临时文件和日志** ```gitignore # 日志 *.log *.tmp *.bak # 编译器缓存 *.cache *.swo ``` --- ## ✅ 三、通配符与模式匹配规则 | 模式 | 说明 | |------|------| | `*.txt` | 忽略所有 `.txt` 文件 | | `/*.txt` | 忽略根目录下的 `.txt` 文件 | | `/dir/` | 忽略根目录下的 `dir` 目录 | | `**/dir/` | 忽略任意位置的 `dir` 目录(递归) | | `!important.txt` | 不忽略 `important.txt` 文件(排除) | --- ## ✅ 四、GitHub 的通用 `.gitignore` 模板 GitHub 提供了多个语言的 `.gitignore` 模板,你可以从这里获取: [https://github.com/github/gitignore](https://github.com/github/gitignore) 例如,如果你用的是 Python,可以直接复制这个模板到你的 `.gitignore` 文件中: ```gitignore # Created by https://www.gitignore.io/api/python ### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ # PyInstaller # Usually these files are created by a pyinstaller build # that's why we ignore them *.manifest *.spec # pytest pytest_cache/ .pytest_cache/ # Jupyter Notebook .ipynb_checkpoints # virtualenv venv/ virtualenv/ env/ ENV/ env.bak/ # pip pip-log.txt pip-delete-this-directory.txt # Setuptools setup.cfg tox.ini ``` --- ## ✅ 五、注意事项 - `.gitignore` 只对未被提交过的文件生效。如果文件已经被提交过,你需要手动删除它或使用 `git rm --cached <file>` 来移除。 - 如果你希望全局忽略某些文件(比如所有项目的 `node_modules`),可以使用 `git config --global core.excludesfile ~/.gitignore_global` 并配置一个全局的 `.gitignore` 文件。 --- 如果你有特定的项目类型(如 Java、Python、Node.js、React 等),我可以为你提供更具体的 `.gitignore` 配置建议!
上一篇:
Git 本地仓库和裸仓库
下一篇:
git撤销pull命令
标题录入,一次不能超过6条
留言
评论