在 shell 中 git clone 仓库的子目录

  1. 复制以下代码到shell的配置文件(如:~/.bashrc 或 ~/.zshrc)中
# specify a directory to git clone
gitcs(){
    
    # extract the content in the url to each variables
    #url="https://github.com/tensorflow/models/tree/master/orbit/examples"

    if [[ -z $1 ]]; then
        echo "usage: gitcs git-clone-url"
        return 1
    fi

    url="$1"
    project_path="${url%/tree/*}"
    echo "project_path: $project_path"

    str="${project_path#*://*/}"
    dir="${str%/*}-${str#*/}"
    echo "dir: $dir"

    str="${url#*/tree/}"
    #echo "$str"
    subdir="${str#*/}"
    echo "subdir: $subdir"

    branch="${str%%/*}"
    echo "$branch"

    create directory and clone
    mkdir "$dir"
    cd "$dir"
    git init 
    git remote add origin "$project_path" # 增加远端的仓库地址
    git config core.sparsecheckout true # 设置Sparse Checkout 为true 
    echo "$subdir" >> .git/info/sparse-checkout # 将要部分clone的目录相对根目录的路径写入配置文件
    git pull origin "$branch" #pull下来代码

}
  1. 读取配置文件
$ source ~/.zshrc
  1. 使用方式
$ gitcs https://github.com/tensorflow/models/tree/master/orbit/examples

参考:

https://zhuanlan.zhihu.com/p/54581830

posted @ 2023-02-06 13:58  3yude  阅读(43)  评论(0)    收藏  举报