首頁·終端機命令

curl

網路

用法

curl [options] <url>

取回一個網址並把正文印到終端機;和瀏覽器不同,不加 `-L` 它不會跟隨轉址,所以遇到 301 看起來像是空回應。

常用選項

選項含義
-LFollow redirects. curl does not follow them on its own, unlike a browser.
-iPrint the response headers along with the body; -I sends HEAD and prints headers only.
-d '{"a":1}'Send a request body. This alone already means POST.
-H "Content-Type: application/json"Add a request header; repeat -H for more.
-X PUTOverride the method. Unnecessary with -d, which is already a POST.
-o <file> / -OSave the body to a file / save it under the remote filename.
-s / -sSNo progress meter / silent but still print errors.
-fExit nonzero on HTTP 4xx and 5xx instead of printing the error page.
-kSkip certificate verification. Debugging only, never in production.

範例

curl -fsSL https://example.com/install.sh -o install.sh

Download quietly, follow redirects, fail loudly on a 404.

curl -i -H "Content-Type: application/json" -d '{"name":"a"}' https://api.example.com/items

POST JSON and read the response headers.

curl -s -o /dev/null -w "%{http_code}\n" https://example.com

Print just the status code.

連不上的時候,這些能把範圍縮小——是名稱解析不了、沒有路由,還是連接埠被擋。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. curl 是做什麼的?

取回一個網址並把正文印到終端機;和瀏覽器不同,不加 `-L` 它不會跟隨轉址,所以遇到 301 看起來像是空回應。

Q. 怎麼寫?

curl [options] <url> —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 9 個,完整列表在 man curl。這條命令屬於網路。

相關命令

man 手冊: man curl