如何从github中克隆指定文件夹

一般来说,我们使用git clone <url> 是会克隆整个仓库下来的,但是某些时候我们可能只需要仓库中的某个/某几个文件夹即可,从而避免下载很多冗余的内容

Git 2.25.0 (Jan 2020)提供了sparse-checkout来实现此内容,一下给出具体代码以及注释。为了方便我将其封装成了脚本,实际运行的时候写进.sh文件中即可

bash 复制代码
#! /bin/bash
tar="$1" localdir="$2" && shift 2
# 参数定义并移除前两个参数

mkdir -p "$localdir"
cd "$localdir"

git clone -n --depth=1 --filter=tree:0 "$tar"
# -n 不进行文件检出 --depth=1 只克隆最近一次提交 --filter=tree:0 只克隆目录结构,不下载实际内容
rep=$(basename "$tar" .git)
# echo "$rep"
cd "$rep"

git sparse-checkout init 
# 初始化 Git 的sparse-checkout,允许只检出仓库中部分目录或文件

git sparse-checkout set --no-cone "$@"
# 指定要检出的文件或目录,$@给出所有参数,注意别用$*
# echo "$@"
git checkout

Usage:

bash 复制代码
./git_sparse_clone https://github.com/gutouyu/ML_CIA.git ./try "Wide&Deep" "DCN"

这里我将代码写进了git_sparse_clone.sh中,前两个参数分别指代目标仓库url以及本地要创建的仓库地址,之后是要克隆的文件夹(们),执行之后就会只克隆第三个参数起指定的目录

注意这个方法对单个文件可能没用,对应措施可以看看这里

相关推荐
go54631584652 小时前
指导初学者使用Anaconda运行GitHub上One - DM项目的步骤
github
时光追逐者15 小时前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
油泼辣子多加1 天前
2025年02月01日Github流行趋势
github
萨文 摩尔杰1 天前
hexo部署到github page时,hexo d后page里面绑定的个人域名消失的问题
github
油泼辣子多加1 天前
2025年01月31日Github流行趋势
github
Ronin-Lotus2 天前
上位机知识篇---Git&GitHub
git·学习·github
AI悦创|编程1v13 天前
GitHub Actions定时任务配置完全指南:从Cron语法到实战示例
github
**kwargs3 天前
ssh密钥登录GitHub时一直提示“Error: Permission denied (publickey)”
运维·ssh·github
dreadp3 天前
解锁豆瓣高清海报:深度爬虫与requests进阶之路
前端·爬虫·python·beautifulsoup·github·requests
江_小_白4 天前
fatal: unable to access ‘https://github
github