【Git学习】 提交时排除文件夹方法——.git-ignore 文件
在 Git 中排除某个文件夹(使其不被提交到远程仓库)有几种方法。以下是主要的解决方案:
方法一:使用 .gitignore 文件(推荐)
gitignore 是 git - ignore(忽略) 的意思,这是最标准的方法,适用于大多数情况。
-
创建或编辑
.gitignore文件:# 如果还没有 .gitignore 文件 touch .gitignore #linux环境下 #Windows环境下,直接右键新建名为 .gitignore 的文件 -
在
.gitignore中添加要排除的文件夹:# 排除单个文件夹 folder_to_exclude/ # 或者使用通配符排除所有类似文件夹 */folder_to_exclude/ # 排除所有名为 node_modules 的文件夹 node_modules/ -
如果文件夹已经被跟踪,需要先将其从 Git 中移除:
# 停止跟踪但保留本地文件 git rm -r --cached folder_to_exclude/ # 提交更改 git add . git commit -m "停止跟踪 folder_to_exclude 文件夹"
方法二:使用 sparse-checkout(高级用法)
如果你想要一个只包含特定文件夹的稀疏检出:
# 启用 sparse-checkout
git config core.sparseCheckout true
# 指定要包含的文件夹
echo "src/" >> .git/info/sparse-checkout
echo "docs/" >> .git/info/sparse-checkout
# 重新读取工作目录
git read-tree -mu HEAD
方法三:从已提交的文件中移除文件夹
如果文件夹已经被提交到了仓库:
# 从 Git 中移除文件夹但保留本地文件
git rm -r --cached folder_to_exclude/
# 提交更改
git commit -m "移除 folder_to_exclude 文件夹"
# 推送到远程
git push origin main
示例 .gitignore 内容
# 排除 node_modules 文件夹
node_modules/
# 排除日志文件夹
logs/
*.log
# 排除编译输出
dist/
build/
# 排除环境变量文件
.env
.env.local
# 排除 IDE 配置文件
.vscode/
.idea/
注意事项
-
.gitignore只对未跟踪的文件有效 - 如果文件已经被 Git 跟踪,需要先使用git rm --cached移除跟踪。 -
.gitignore文件本身需要被提交 - 这样其他协作者也会应用相同的忽略规则。 -
使用全局忽略 - 你也可以设置全局忽略规则:
git config --global core.excludesfile ~/.gitignore_global
选择最适合你需求的方法。对于大多数情况,使用 .gitignore 文件是最简单有效的解决方案。
常用 .gitignore 模版
# 编译生成文件
*.o
*.obj
*.elf
*.hex
*.bin
*.map
*.lst
*.d
*.su
# 构建目录
build/
obj/
Debug/
Release/
output/
dist/
bin/
# 临时文件
*.tmp
*.swp
*~
*.swo
.DS_Store
._*
# 项目文件
.project
.cproject
.settings/
# 版本控制系统
.git
.svn
# IDE 相关
.vscode/
.vs/
.idea/
*.code-workspace
# 编辑器临时文件
*.bak
*.orig
*.rej
# 工具链生成文件
*.depend
*.layout
*.pyc
__pycache__/
# FreeRTOS 特定
# 自动生成的配置文件
FreeRTOSConfig.h.bak
*.autogen.*
# 日志文件
*.log
*.trace
# 依赖管理
dependencies/
lib/
*.a
*.so
*.lib
*.dll
# 测试相关
test_results/
*.gcov
*.gcda
*.gcno
# 文档生成
docs/_build/
docs/_out/
doxygen/
# 压缩包
*.zip
*.tar.gz
*.7z
*.rar
# 平台特定
# Windows
Thumbs.db
ehthumbs.db
Desktop.ini
# Linux
.*.swp
.*.swo
.fuse_hidden*
# macOS
.DS_Store
.AppleDouble
.LSOverride
.Spotlight-V100
.Trashes

浙公网安备 33010602011771号