如何:並發 cURL 下載?

如何:並發 cURL 下載?

如何使用curl同時下載多個檔案?即使我們需要產生多個curl進程,我該如何從命令列或shell函數來完成?例如:

$ multiCurl <download 1> <download 2> <download 3>

multiCurl () {
  curl <download 1>
  curl <download 2>
  curl <download 3>
}

或者

for link in $(cat download.list); do
  curl <link 1>
  curl <link 2>
  curl <link 3>
  curl <link 4>
done

答案1

也許您可以使用命令parallel同時下載多個檔案。

這裡我假設你保留原始檔名

#!/usr/bin/env bash

funcDownloadOperation(){
    link="${1:-}"
    curl -fsSL -O "${link}"
    if [[ -s "${link##*/}" ]]; then
        echo "file ${link##*/} download successfully!"
    else
        echo "fail to download link ${link}"
    fi
}

export -f funcDownloadOperation
cat download.list | parallel -k -j 0 funcDownloadOperation

您需要parallel在 Linux 系統中手動安裝實用程式。

答案2

&只需在每個命令的末尾添加即可使其在背景執行:

curl <link 1>&

畢竟,這一切都取決於您是否還想知道這些命令何時結束以及它們的回傳代碼是什麼。如果是這樣,您想嘗試以下操作:

set -a pids # Array of the process ids of background commands
for url in $whatever_the_list_of_urls 
do
    curl $url&  # start CURL in background
    pids[${#pids[*]}]=$! # remember PID 
done

# all started, now wait for them
for pid in ${pids[*]}
do
    wait $pid 
    print "Sensed end of $pid, rc:=$?"
done

相關內容