創用 CC 授權條款
除非另有註明,本網站的著作Fygul Hether製作,以創用CC 姓名標示-非商業性-禁止改作 4.0 國際 授權條款釋出。

2020年6月14日 星期日

curl使用簡介

摘要

本文簡單介紹curl及其使用法。

curl簡介

如果讀者經常使用開源軟件,可能會發現有些開源軟件的安裝工作時會利用curlwget來下載安裝程式,像Node.js與Calibre的Linux版就分別用這兩者。而uGet下載管理器也使用curl。

curl是開源軟件,包含命令行CLI的curl執行檔與libcurl函式庫,本文主要講前者。1997年開始釋出,經過幾次改名,最終改成代表Client URL的目前名字。curl可用來對服務器傳輸(上傳或下載)資料,支援眾多傳輸協定、proxy、用戶驗證、SSL、cookies、續傳……,功能相當多。

下載安裝curl

在Ubuntu中curl並非預裝,安裝很容易:

$ sudo apt install curl
Windows機器則可到官方下載頁找DOS版的二進制檔案的壓縮檔,內含執行檔與說明文件。沒實際用過,不過應該是解開後找到執行檔照一般命令行執行檔使用即可。

使用

顯示使用文件

顯示幫助文字,內容也挺長的:

$ curl --help
也可以這樣顯示manpage的內容(很長,可轉向存成文字檔):

$ curl --manual
顯示版本資訊,也會顯示支援的協定與功能:

$ curl --version
上述三者短式選項分別是-h, -M, -V

命令形式


curl [options] <url>
URL的語法依傳輸協定而異。可以在URL中使用 {}[] 來代表多個項目,如[a-z]的表示法,但以下為求簡單,僅以單一項目做說明。

較常用選項

除了上面提到的幾個,這裡列一些下載資料時較常用的選項:

     --connect-timeout <seconds> Maximum time allowed for connection
--create-dirs Create necessary local directory hierarchy
-f, --fail Fail silently (no output at all) on HTTP errors
-I, --head Show document info only
--limit-rate <speed> Limit transfer speed to RATE
-L, --location Follow redirects
--max-filesize <bytes> Maximum file size to download
--max-redirs <num> Maximum number of redirects allowed
-m, --max-time <time> Maximum time allowed for the transfer
-o, --output <file> Write to file instead of stdout
--proto <protocols> Enable/disable PROTOCOLS
-R, --remote-time Set the remote file's time on the local output
--retry <num> Retry request if transient problems occur
--retry-connrefused Retry on connection refused (use with --retry)
--retry-delay <seconds> Wait time between retries
--retry-max-time <seconds> Retry only within this period
-S, --show-error Show error even when -s is used
-s, --silent Silent mode
-Y, --speed-limit <speed> Stop transfers slower than this
-y, --speed-time <seconds> Trigger 'speed-limit' abort after this time
-1, --tlsv1 Use TLSv1.0 or greater
--tlsv1.0 Use TLSv1.0
--tlsv1.1 Use TLSv1.1
--tlsv1.2 Use TLSv1.2
--tlsv1.3 Use TLSv1.3
-A, --user-agent <name> Send User-Agent <name> to server
-v, --verbose Make the operation more talkative

簡單範例

取得某個(虛構)檔案,存在家目錄下的子目錄,自動建立此目錄:

$ curl -sSL http://example.org/afile.tgz -o ~/folder/afile.tgz --create-dirs
查看某(虛構)網站的header資料:

$ curl -I http://example.org

結語

以上只談了幾個以curl做下載工作的簡單使用法,沒有談到其他方面的使用,像網頁表單、FTP、接收/寄送郵件之類,詳細的用法可見官方文件、書[1]或Manpage。

參考

  1. curl官網:除了官方說明文件,還有本書Everython curl,有中文版,見[2]。
  2. 中文維基百科cURL條目
  3. 英文維基百科cURL條目
  4. Ubuntu Manpage: curl

沒有留言:

張貼留言