curl 是功能最完整的命令列傳輸工具,支援 HTTP/HTTPS/FTP/SFTP 等協議,廣泛用於 API 測試、自動化腳本、檔案下載上傳。本文整理 11 大實戰場景與常用參數速查表,助你掌握 curl 核心用法。
| 參數 | 長參數 | 說明 |
|---|---|---|
-O | --remote-name | 以遠端檔名儲存 |
-o | --output | 指定輸出檔名 |
-C - | --continue-at - | 斷點續傳 |
-L | --location | 追蹤重導向 |
-H | --header | 自訂請求標頭 |
-d | --data | POST 資料 |
-b | --cookie | 送出 Cookie |
-c | --cookie-jar | 儲存 Cookie 到檔案 |
-A | --user-agent | 偽裝 User-Agent |
-e | --referer | 偽裝 Referer |
-x | --proxy | 指定 HTTP 代理 |
-u | --user | 基本認證 user:pass |
-s | --silent | 靜默模式 |
-# | --progress-bar | 進度條顯示 |
-I | --head | 只取得 HEAD 回應 |
-v | --verbose | 詳細輸出 |
$ curl https://www.example.com
無桌面環境的伺服器常用此法測試網站可達性。
# 重導向
$ curl https://www.example.com > page.html
# -o 指定檔名(顯示進度)
$ curl -o page.html https://www.example.com
# -O 使用遠端檔名(需具體檔案 URL)
$ curl -O https://www.example.com/file.zip
$ curl -o /dev/null -s -w "%{http_code}" https://www.example.com
# 輸出如:200
$ curl -x 192.168.1.100:8080 https://www.example.com
# 儲存回應 Cookie
$ curl -c cookies.txt https://www.example.com
# 儲存回應 Header(含 Set-Cookie)
$ curl -D headers.txt https://www.example.com
# 送出 Cookie
$ curl -b cookies.txt https://www.example.com
$ curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" https://www.example.com
$ curl -e "https://www.example.com/" https://www.example.com/protected.jpg
# 循環下載多檔案
$ curl -O https://example.com/img[1-10].jpg
# 多目錄下載並重命名避免覆蓋
$ curl -o "#1_#2.jpg" https://example.com/{dir1,dir2}/img[1-5].jpg
# 輸出:dir1_img1.jpg, dir1_img2.jpg, ..., dir2_img5.jpg
# 分段下載大檔案
$ curl -r 0-1023999 -o part1.bin https://example.com/large.bin
$ curl -r 1024000-2047999 -o part2.bin https://example.com/large.bin
$ curl -r 2048000- -o part3.bin https://example.com/large.bin
$ cat part*.bin > large.bin
# FTP 下載(兩種語法)
$ curl -O -u user:pass ftp://example.com/file.zip
$ curl -O ftp://user:pass@example.com/file.zip
# 進度條 / 靜默
$ curl -# -O https://example.com/large.iso
$ curl -s -O https://example.com/large.iso
$ curl -C - -O https://example.com/large.iso
$ curl -T localfile.txt -u user:pass ftp://example.com/upload/
# HTTP POST 上傳
$ curl -F "file=@localfile.txt" https://example.com/upload
# 失敗時不輸出 HTTP 錯誤頁面,只回傳錯誤碼
$ curl -f https://example.com/notfound
# 結合腳本判斷
$ if curl -f -o /dev/null -s https://example.com; then echo "OK"; else echo "FAIL"; fi
--limit-rate 100k # 限速
--max-time 30 # 最大執行秒數
--connect-timeout 10 # 連線逾時
--retry 3 # 重試次數
--retry-delay 5 # 重試間隔
--compressed # 請求 gzip/deflate 壓縮
-k / --insecure # 忽略 SSL 憑證驗證(測試用)