Bash

使用 cURL、jq 和聲明以及 for 循環條件,我嘗試從 GitLab 私人倉庫下載多個文件,但它只下載了一個

  • June 1, 2020

我從以下來源了解到:

腳本說明:

  1. GitLab 的儲存庫文件 API所需的變數:
branch="master"
repo="my-dotfiles"
private_token="XXY_wwwwwx-qQQQRRSSS"
username="gusbemacbe"
  1. 我對多個文件使用了聲明:
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"
)
  1. 我使用條件for循環jq將所有文件從聲明轉換context_dirs為編碼 URL:
for urlencode in "${context_dirs[@]}"; do
 paths=$(jq -nr --arg v "$urlencode" '$v|@uri')
done
  1. 我使用條件for循環下載了curlpaths轉換為jq. 我使用-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循環只輸出一個編碼路徑並且只下載一個文件。

第一個循環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

引用自:https://unix.stackexchange.com/questions/590191