使用 cURL、jq、声明和 for 循环条件,我尝试从 GitLab 私有存储库下载多个文件,但它只下载了一个

使用 cURL、jq、声明和 for 循环条件,我尝试从 GitLab 私有存储库下载多个文件,但它只下载了一个

我从以下来源了解到:

脚本说明:

  1. 变量,GitLab 所需的存储库文件 API

    branch="master"
    repo="my-dotfiles"
    private_token="XXY_wwwwwx-qQQQRRSSS"
    username="gusbemacbe"
    
  2. 我对多个文件使用了声明:

    declare -a context_dirs=(
      "home/.config/Code - Insiders/Preferences"
      "home/.config/Code - Insiders/languagepacks.json"
      "home/.config/Code - Insiders/rapid_render.json"
      "home/.config/Code - Insiders/storage.json"
    )
    
  3. 我使用条件for循环将jq所有文件从声明转换context_dirs为编码 URL:

    for urlencode in "${context_dirs[@]}"; do
      paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
    done
    
  4. 我使用条件for循环来下载从转换后curl获取的多个文件。重要的是我使用和来输出文件名,并且for :pathsjq-0-J-H"PRIVATE-TOKEN: $private_token"

    for file in "${paths[@]}"; do 
        curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
    done
    

完整源代码:

branch="master"
id="1911000X"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"

declare -a context_dirs=(
  "home/.config/Code - Insiders/Preferences"
  "home/.config/Code - Insiders/languagepacks.json"
  "home/.config/Code - Insiders/rapid_render.json"
  "home/.config/Code - Insiders/storage.json"
)

for urlencode in "${context_dirs[@]}"; do
  paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done

for file in "${paths[@]}"; do 
    curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
done

但这两个条件for循环仅输出编码路径并仅下载文件。

答案1

paths第一个循环在每次迭代中覆盖变量的值。由于您稍后希望这是一个数组,因此请确保它已正确创建:

paths=()
for urlencode in "${context_dirs[@]}"; do
  paths+=( "$(jq -nr --arg v "$urlencode" '$v|@uri')" )
done

或者,组合两个循环:

for urlencode in "${context_dirs[@]}"; do
  file=$(jq -nr --arg v "$urlencode" '$v|@uri')
  curl -sLOJH "PRIVATE-TOKEN: $private_token" "https://gitlab.com/api/v4/projects/$username%2F$repo/repository/files/$file/raw?ref=$branch"
done

相关内容