You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CLI下载GitHub仓库中的子文件夹或文件

多Git仓库指定子文件夹拉取方案及自动化实现

方案1:原生Git sparse-checkout 批量脚本(保留版本追踪,适配你现有使用习惯)

该方案基于你已经验证过的sparse-checkout能力实现,原生Git支持,无需安装额外工具,适合需要后续同步仓库更新、保留提交记录的场景。

前置要求

  • Git版本≥2.25.0(低版本兼容方法见文末说明)
  • Git Bash环境可正常运行shell脚本

操作步骤

  1. 新建仓库配置文件repo_list.conf,每行定义一个待拉取仓库的信息,格式为仓库地址 本地存储路径 要拉取的子文件夹1 子文件夹2...,示例如下:
https://github.com/yourname/projectA.git ./projectA src/utils docs
https://github.com/yourname/projectB.git ./projectB config static/css
# 注释行以#开头,会被自动跳过
  1. 新建批量处理脚本batch_sparse_pull.sh,内容如下:
#!/bin/bash
CONFIG_FILE="./repo_list.conf"
# 可修改为你需要拉取的默认分支,比如master
DEFAULT_BRANCH="main"

while read -r repo_url local_dir subdirs || [ -n "$repo_url" ]; do
    [[ -z "$repo_url" || "$repo_url" =~ ^#.* ]] && continue
    echo "正在处理:$repo_url"

    if [ ! -d "$local_dir/.git" ]; then
        # 首次拉取初始化
        mkdir -p "$local_dir" && cd "$local_dir"
        git init
        git remote add origin "$repo_url"
        git config core.sparseCheckout true
        for subdir in $subdirs; do
            echo "$subdir/*" >> .git/info/sparse-checkout
        done
        git pull origin "$DEFAULT_BRANCH"
        cd - > /dev/null
    else
        # 已有仓库更新规则+拉取最新代码
        cd "$local_dir"
        > .git/info/sparse-checkout
        for subdir in $subdirs; do
            echo "$subdir/*" >> .git/info/sparse-checkout
        done
        git pull origin "$DEFAULT_BRANCH"
        cd - > /dev/null
    fi
done < "$CONFIG_FILE"
  1. 在Git Bash中执行以下命令运行脚本:
chmod +x batch_sparse_pull.sh
./batch_sparse_pull.sh

方案2:轻量一次性导出(无需保留Git记录,速度更快)

如果你只是需要一次性导出子文件夹内容,不需要后续同步版本,可使用git archive实现,本地不会生成冗余的.git目录,占用空间更小。

单仓库执行命令示例:

从远程仓库的main分支拉取src/utils目录,解压到本地./my_utils文件夹:

git archive --remote=https://github.com/yourname/projectA.git main:src/utils | tar -x -C ./my_utils

你也可以参考方案1的配置文件读取逻辑,将该命令封装为批量脚本使用。

方案3:多仓库子文件夹合并到单个本地Git仓库

如果你需要把所有拉取的子文件夹整合到同一个本地Git仓库中做统一管理,推荐使用git submodule+sparse-checkout的组合方案:

  1. 初始化你的统一管理仓库:
git init local_union_repo && cd local_union_repo
  1. 为每个待引入的仓库添加子模块,并开启稀疏检出:
# 示例:引入projectA的src/utils目录到当前仓库的external/utils路径
git submodule add https://github.com/yourname/projectA.git external/utils
cd external/utils
git sparse-checkout set src/utils
mv src/utils/* . && rm -rf src
cd ../../
git add .gitmodules external/utils
git commit -m "引入projectA的utils模块"

后续批量更新所有子模块的内容只需执行:git submodule update --remote --merge

注意事项

  • 拉取私有仓库时,可在仓库地址中携带认证token,格式为https://<你的访问token>@github.com/yourname/projectA.git
  • Git版本低于2.25.0时,只需在脚本的git init步骤后添加一行git config core.sparseCheckout true即可正常运行
  • 使用SSH地址拉取仓库时,提前将本地SSH公钥配置到对应Git托管平台,避免重复输入密码

内容的提问来源于stack exchange,提问作者Caleb Adepoju

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 10:57:06