Skip to content

curl チートシート

URL でデータを転送するためのコマンドラインツール。

01

はじめに

基本のリクエスト

curl はコマンドラインから HTTP リクエストを送ります。デフォルトは GET です。-v で詳細出力、-o で名前を付けたファイルへ保存、-O でリモートのファイル名を維持、-L でリダイレクトを追跡、-I でヘッダーだけ取得(HEAD リクエスト)します。

curl
# GET request (default)
curl https://example.com

# with verbose output
curl -v https://example.com

# save output to file
curl -o output.html https://example.com
curl -O https://example.com/file.zip   # keep remote filename

# follow redirects
curl -L https://example.com/redirect

# show only headers
curl -I https://example.com
curl --head https://example.com

出力と保存

-o はボディを指定した名前のファイルへ書き込み、-O はリモートのファイル名を使います。--output-dir で保存先ディレクトリを設定します。-s(silent)は進捗メーターとエラーを抑制します — エラーだけは表示したい場合 -S とペアにしましょう。-D でヘッダーをファイルへダンプし、-o /dev/null でボディを破棄できます。

curl
# print body to stdout (default)
curl https://example.com

# save body to file
curl -o page.html https://example.com

# save with remote filename
curl -O https://example.com/file.zip

# save to specific dir with remote name
curl -O --output-dir /tmp https://example.com/file.zip

# append to file
curl https://example.com >> log.txt

# discard body, keep headers
curl -o /dev/null -D headers.txt https://example.com

# silent (no progress, no errors)
curl -s https://example.com

詳細出力とヘッダー

-v(verbose)はやり取り全体を出力します:'>' がリクエスト、'<' がレスポンス、'*' が curl の情報 — すべて stderr へ出力されるため、stdout はボディ用にきれいなままです。-I は HEAD リクエストを送りヘッダーを表示します。-D でヘッダーをファイルか '-'(stdout)へダンプし、-o /dev/null と組み合わせればボディを保存せずにヘッダーを確認できます。

curl
# verbose: shows request + response, sent to stderr
curl -v https://example.com

# > lines are the request, < lines are the response
# * lines are curl's internal info

# headers only (HEAD request)
curl -I https://example.com

# dump response headers to file
curl -D headers.txt -o body.html https://example.com

# dump headers to stdout, body to file
curl -D - -o body.html https://example.com

# show only response headers (no HEAD)
curl -s -o /dev/null -D - https://example.com

リダイレクトの追跡

-L は HTTP 3xx リダイレクトを追跡します。デフォルトでは最大 50 ホップまで(--max-redirs で上限設定)。RFC 301/302 では通常 POST が GET に変わります — メソッドを維持するには --post301/--post302 を使いましょう。デフォルトでは認証情報はリダイレクト先のホストへ送られません。--location-trusted はどこへでも送ります(セキュリティリスクあり)。

curl
# follow 3xx redirects
curl -L https://example.com/old

# limit number of redirects
curl -L --max-redirs 5 https://example.com

# treat redirects as POST (default resends as GET)
curl -L --post301 --post302 https://example.com

# show each hop in a redirect chain
curl -L -v https://short.url/abc 2>&1 | grep -i location

# follow only http/https redirects
curl -L --proto-redir http,https https://example.com

# send credentials only on first request
curl -L --location-trusted -u user:pass https://example.com

URL 構文とグロビング

curl は URL の「グロビング」パターンを展開します:[1-10] の範囲、{a,b,c} のリスト、省略可能な :step。各展開が個別のリクエストになります。-g(--globoff)で括弧と波括弧をリテラル扱いにできます — JSON 配列や http://[::1]:8080/ のような IPv6 アドレスを含む URL には重要です。

curl
# range glob: requests file1, file2, file3
curl -O https://example.com/file[1-3].zip

# range with step
curl -O https://example.com/file[1-10:2].zip   # 1,3,5,7,9

# list glob: a, b, c
curl -O https://example.com/{a,b,c}.zip

# combined globs
curl -O https://example.com/{v1,v2}/file[1-2].txt

# output each URL as it is fetched
curl -O https://example.com/file[1-3].zip --write-out "%{url} -> %{filename}\n"

# disable globbing (literal brackets/braces)
curl -g "https://example.com/file[1].zip"

ヘルプとバージョン

--version は curl のバージョン、サポートするプロトコル(HTTP、HTTPS、FTP など)、組み込み機能(HTTP2、SSL、brotli)を表示します。--help all ですべてのオプションを一覧できます — フラグ名の一部しか覚えていないときに便利です。機能は curl のビルド方法に依存します(例:HTTP/3 は特別なビルドが必要)。

curl
# version and supported features
curl --version

# short help (one-line per option)
curl --help

# long help (all options with details)
curl --help all

# search help for a keyword
curl --help all | grep -i cookie

# list supported protocols
curl --version | head -1

# check if a feature is built in
curl --version | grep -i http2
02

HTTP メソッド

GET リクエスト

GET はデフォルトのメソッドです。& や ? を含む URL は必ず引用符で囲みましょう — シェルにバックグラウンド処理や展開をされないためです。-X でメソッドを明示できますが、GET には通常不要です。API では Accept を設定してレスポンス形式を交渉しましょう。

curl
# simple GET (default method)
curl https://api.example.com/data

# GET with query string
curl "https://api.example.com/search?q=curl&page=2"

# explicit method
curl -X GET https://example.com

# GET with headers
curl -H "Accept: application/json" https://api.example.com/data

# GET with auth
curl -u user:pass https://api.example.com/secret

POST リクエスト

-d を送るとメソッドが自動的に POST に切り替わるため、-X POST は冗長です(無害で分かりやすくはありますが)。ファイルを POST するには -d @filename を使います(@ がファイル読み込みを意味します)。-d のデフォルト Content-Type は application/x-www-form-urlencoded です。JSON には -H で上書きしましょう。

curl
# POST with form data (application/x-www-form-urlencoded)
curl -X POST -d "name=Alice&age=30" https://api.example.com/users

# -d implies POST, so -X is optional
curl -d "name=Alice" https://api.example.com/users

# POST with no body
curl -X POST https://api.example.com/trigger

# POST JSON
curl -X POST -H "Content-Type: application/json" \
     -d '{"name":"Alice"}' https://api.example.com/users

# POST with data from a file
curl -X POST -d @form.txt https://api.example.com/users

PUT と PATCH

PUT はリソース全体を置き換え、PATCH は部分的な更新を適用します。どちらも curl に専用の -d ショートカットがないため -X が必要です。-T(upload-file)はファイルをリクエストボディとしてストリーミングし、PUT アップロードに最適です。生のファイルを送るときに改行が削られるのを避けるには、-d の代わりに --data-binary を使います。

curl
# PUT (replace entire resource)
curl -X PUT -H "Content-Type: application/json" \
     -d '{"name":"Alice","age":31}' \
     https://api.example.com/users/1

# PATCH (partial update)
curl -X PATCH -H "Content-Type: application/json" \
     -d '{"age":32}' \
     https://api.example.com/users/1

# PUT a file as body
curl -X PUT --data-binary @config.json \
     -H "Content-Type: application/json" \
     https://api.example.com/config

# PUT with upload file
curl -X PUT -T localfile.txt https://example.com/remote.txt

DELETE

DELETE はリソースを削除します。多くの API は認証を要求するため、-u か Authorization ヘッダーを含めましょう。ボディを受け付ける API もあります(理由、カスケードフラグ)— -d と Content-Type ヘッダーを追加します。結果の確認には -w '%{http_code}' を使いましょう:204(No Content)と 200 が典型的な成功です。

curl
# delete a resource
curl -X DELETE https://api.example.com/users/1

# delete with auth
curl -X DELETE -H "Authorization: Bearer TOKEN" \
     https://api.example.com/users/1

# delete with confirmation check
curl -X DELETE -w "%{http_code}" -o /dev/null -s \
     https://api.example.com/users/1

# delete with request body (some APIs require it)
curl -X DELETE -H "Content-Type: application/json" \
     -d '{"reason":"spam"}' \
     https://api.example.com/users/1

HEAD と OPTIONS

-I は HEAD リクエスト(ヘッダーのみ、ボディなし)を送ります — ダウンロードせずにサイズ(Content-Length)、タイプ(Content-Type)、最終更新を確認するのに有用です。OPTIONS は許可されたメソッド(Allow ヘッダー)を示し、ブラウザの CORS プリフライトで使われます。本物のプリフライトをシミュレートするには、Origin と Access-Control-Request-Method ヘッダーを加えましょう。

curl
# HEAD: headers only, no body
curl -I https://example.com
curl --head https://example.com

# OPTIONS: discover allowed methods
curl -X OPTIONS https://api.example.com/users

# OPTIONS with CORS preflight headers
curl -X OPTIONS \
     -H "Origin: https://mysite.com" \
     -H "Access-Control-Request-Method: POST" \
     https://api.example.com/users

# check allowed methods from Allow header
curl -X OPTIONS -s -D - -o /dev/null https://api.example.com | grep -i allow
03

ヘッダー

ヘッダーの設定(-H)

-H(--header)はリクエストヘッダーを追加します。複数のヘッダーには -H を繰り返します。末尾のセミコロン(X-Empty;)は空の値を送ります。@headers.txt はヘッダーをファイルから読み込みます(1 行に 'Name: value')— Authorization トークンをシェルの履歴から離しておくのに便利です。

curl
# single header
curl -H "Accept: application/json" https://api.example.com/data

# multiple headers
curl -H "Accept: application/json" \
     -H "Authorization: Bearer TOKEN" \
     -H "X-Custom: value" \
     https://api.example.com/data

# header with empty value
curl -H "X-Empty;" https://example.com

# headers from a file (one per line)
curl -H @headers.txt https://example.com

# Content-Type for POST
curl -X POST -H "Content-Type: application/json" \
     -d '{"a":1}' https://api.example.com

よく使うヘッダー

最もよく使うヘッダー:Accept は欲しい形式をサーバーに伝え、Content-Type はリクエストボディを説明し、Authorization が認証情報を運びます。--compressed は curl に圧縮レスポンス(gzip、br)を要求させ、自動で展開します — エンコードを手で処理する必要がありません。

curl
# Accept: negotiate response format
curl -H "Accept: application/json" https://api.example.com
curl -H "Accept: text/html" https://example.com

# Content-Type: describe request body
curl -H "Content-Type: application/json" -d '{"a":1}' https://api.example.com
curl -H "Content-Type: application/x-www-form-urlencoded" -d "a=1" https://api.example.com

# Authorization: credentials
curl -H "Authorization: Bearer TOKEN" https://api.example.com

# Accept-Encoding: ask for compression
curl -H "Accept-Encoding: gzip, br" --compressed https://example.com

# Cache-Control
curl -H "Cache-Control: no-cache" https://api.example.com

User-Agent

デフォルトの curl の User-Agent をブロックするサーバーもあります。-A(--user-agent)で設定でき、空の -A で完全に取り除けます。長い形式は -H 'User-Agent: ...' です。スクレイピング防止のサイトの多くは本物のブラウザのシグネチャをチェックするため、現実的なブラウザ UA がしばしば必要です。

curl
# default User-Agent looks like: curl/8.7.1
curl -v https://example.com 2>&1 | grep -i user-agent

# set a custom User-Agent
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://example.com
curl -H "User-Agent: MyBot/1.0" https://example.com

# empty User-Agent
curl -A "" https://example.com

# fake a real browser (some sites require it)
curl -A "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) \
AppleWebKit/537.36 (KHTML, like Gecko) \
Chrome/120.0 Safari/537.36" https://example.com

# per-site default via config
# user-agent = "MyBot/1.0"  in ~/.curlrc

Referer と Host

-e(--referer)は Referer ヘッダーを設定します。IP でバーチャルホストをテストするときは Host の上書きが不可欠です — サーバーが Host に基づいて正しいサイトを選びます。CORS 対応のエンドポイントは Origin を要求することが多く、X-Forwarded-For/Proto はプロキシやロードバランサーの後ろのリクエストをシミュレートします。

curl
# set Referer header
curl -H "Referer: https://google.com" https://example.com/page
curl -e https://google.com https://example.com/page

# set Host header (override DNS)
curl -H "Host: api.example.com" https://192.168.1.10/users

# combined: test a vhost by IP with custom Host
curl -H "Host: api.example.com" \
     -H "X-Forwarded-Proto: https" \
     http://10.0.0.5/health

# Origin header (for CORS/POST forms)
curl -H "Origin: https://mysite.com" \
     -X POST -d "x=1" https://api.example.com/form

# X-Forwarded-For (debugging proxies)
curl -H "X-Forwarded-For: 1.2.3.4" https://api.example.com

ヘッダーの削除

-H 'Header-Name:'(コロン付きで値なし)を渡すと、curl はそのヘッダーに値を送らず、User-Agent や Accept-Encoding のようなデフォルトヘッダーを実効的に削除します。curl は同じ名前のヘッダーを再指定すると置き換えます(重複送信しません)。最小限のリクエストを送るときに有用です。

curl
# remove a header by giving it no value
curl -H "User-Agent:" https://example.com

# remove Accept-Encoding (disable compression)
curl -H "Accept-Encoding:" https://example.com

# remove all auto-added headers and send minimal request
curl -H "Host:" -H "User-Agent:" -H "Accept:" https://example.com

# prevent curl from adding Accept-Encoding
curl --no-keepalive https://example.com

# replace a default header instead of adding a duplicate
# (curl replaces, doesn't duplicate, when -H name matches)
curl -H "Accept: text/plain" https://example.com
04

POST データとフォーム

フォームデータ(-d)

-d(--data)は URL エンコードされたフォームデータを送り、メソッドを POST に切り替えます。複数の -d フラグは & で結合されます。-d は先頭/末尾の空白と改行を削りますが、--data-binary は保持し、--data-raw は @file 機能を完全に無効化します(@ で始まるリテラル値がそのまま送られます)。

curl
# URL-encoded form data
curl -d "name=Alice&age=30" https://api.example.com/form

# explicit POST (same result; -d implies POST)
curl -X POST -d "name=Alice" https://api.example.com/form

# multiple -d are joined with &
curl -d "name=Alice" -d "age=30" https://api.example.com/form

# -d strips newlines; use --data-binary to preserve them
curl --data-binary "line1\nline2" https://api.example.com

# raw data, no content-type added
curl --data-raw "name=Alice&age=30" https://api.example.com

# default Content-Type: application/x-www-form-urlencoded
curl -v -d "a=1" https://api.example.com 2>&1 | grep -i content-type

URL エンコード

--data-urlencode は値(または name=value 全体)をパーセントエンコードします — スペース、&、=、非 ASCII を手でエンコードする必要がありません。name@file では、ファイルの内容が値として URL エンコードされます。フォーム構造を壊さないため、ユーザー提供のデータには必ずこれを使いましょう。

curl
# spaces and special chars must be encoded
curl -d "name=Alice%20Smith" https://api.example.com
curl -d "name=Alice+Smith" https://api.example.com

# --data-urlencode encodes the value for you
curl --data-urlencode "name=Alice Smith" https://api.example.com
curl --data-urlencode "[email protected]" https://api.example.com

# encode name=value pair (both encoded)
curl --data-urlencode "name=Alice & Bob" https://api.example.com

# encode only the value after =, with explicit content-type
curl --data-urlencode "query=SELECT * FROM users" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     https://api.example.com/search

# encode content of a file
curl --data-urlencode [email protected] https://api.example.com

バイナリデータ

--data-binary はファイルをバイト単位で送ります(改行と null バイトを保持)— 削ってしまう -d とは違います。-T はファイルをストリーミングするため、大きなアップロードでもメモリ使用量が低く保たれます。事前に圧縮したデータを送るには、-H 'Content-Encoding: gzip' でパイプしましょう — サーバーが対応している必要があります。対応していなければ Transfer-Encoding: chunked を使います。

curl
# send a binary file as the body
curl --data-binary @image.png https://api.example.com/upload

# upload with explicit content type
curl --data-binary @image.png \
     -H "Content-Type: image/png" \
     https://api.example.com/upload

# raw bytes (no @ expansion, no stripping)
curl --data-raw "$(printf '\x00\x01\x02')" https://api.example.com

# stream a large file without buffering in memory
curl -T bigfile.iso https://api.example.com/upload

# send gzipped body
gzip -c data.json | curl --data-binary @- \
     -H "Content-Encoding: gzip" \
     -H "Content-Type: application/json" \
     https://api.example.com/data

ファイルからの読み込み(@file)

-d @file はリクエストボディをファイルから読み込みます(@ がファイル読み込みをトリガーします)。--data-binary @file はバイトを保持します。-d @- は stdin から読み込みます — jq や他の変換のパイプに最適です。@ で始まるリテラル値がありファイル展開を望まない場合は --data-raw を使いましょう。

curl
# read body from a file
curl -d @data.txt https://api.example.com/form

# read JSON body from a file
curl -H "Content-Type: application/json" \
     -d @payload.json https://api.example.com

# binary-safe file read
curl --data-binary @image.png https://api.example.com/upload

# read from stdin
echo '{"a":1}' | curl -d @- https://api.example.com

# pipe through curl (transform then send)
jq '{name, age}' input.json | \
  curl -H "Content-Type: application/json" -d @- https://api.example.com

# file name starting with @ (use --data-raw)
curl --data-raw "@mention" https://api.example.com

Content-Type とフォーム

Content-Type は必ずボディ形式に合わせましょう:application/x-www-form-urlencoded(-d のデフォルト)、application/json(-H と共に)、multipart/form-data(-F が自動設定)、text/xml(SOAP 用)。非 ASCII データには charset=utf-8 を加えるのが良い慣習です。不一致があると、サーバーはボディを拒否するか誤ってパースします。

curl
# default for -d: application/x-www-form-urlencoded
curl -d "name=Alice" https://api.example.com

# JSON body
curl -H "Content-Type: application/json" \
     -d '{"name":"Alice"}' https://api.example.com

# multipart form (file upload, see File Upload section)
curl -F "[email protected]" https://api.example.com/upload

# text/plain body
curl -H "Content-Type: text/plain" -d "hello" https://api.example.com

# XML body (SOAP)
curl -H "Content-Type: text/xml" \
     -d '<?xml version="1.0"?><env:Envelope/>' \
     https://api.example.com/soap

# set charset explicitly
curl -H "Content-Type: application/json; charset=utf-8" \
     -d '{"name":"éàç"}' https://api.example.com
05

JSON リクエスト

基本の JSON POST

JSON リクエストには -H 'Content-Type: application/json' と、JSON 文字列の -d が必要です。JSON はシングルクォートで囲みましょう — 内側のダブルクォートをシェルに触らせないためです。レスポンスを jq '.' にパイプすれば読みやすい出力になり、jq '.field' で特定の値を取り出せます。

curl
# JSON POST request
curl -X POST \
     -H "Content-Type: application/json" \
     -d '{"name":"Alice","age":30}' \
     https://api.example.com/users

# -d already implies POST, so -X is optional
curl -H "Content-Type: application/json" \
     -d '{"name":"Alice"}' \
     https://api.example.com/users

# ask for JSON back
curl -H "Accept: application/json" \
     -H "Content-Type: application/json" \
     -d '{"name":"Alice"}' \
     https://api.example.com/users

# pretty-print the JSON response (pipe to jq)
curl -s -H "Accept: application/json" \
     https://api.example.com/users/1 | jq .

ファイルからの JSON

複雑な JSON は .json ファイルに保存し、-d @file(改行を含む正確なバイトを保持する --data-binary @file)を使いましょう。jq -n へのパイプで、面倒なエスケープなしにプログラム的に JSON を組み立てられます。まず必ず jq . で検証しましょう — 構文エラーはリクエスト 1 回分を無駄にします。

curl
# POST JSON body from a file
curl -H "Content-Type: application/json" \
     -d @payload.json https://api.example.com/users

# binary-safe (preserves exact bytes)
curl -H "Content-Type: application/json" \
     --data-binary @payload.json https://api.example.com/users

# generate JSON with jq, then POST
jq -n '{name: "Alice", age: 30}' | \
  curl -H "Content-Type: application/json" \
       -d @- https://api.example.com/users

# validate JSON before sending
jq . payload.json && \
  curl -H "Content-Type: application/json" \
       -d @payload.json https://api.example.com/users

# send a JSON array
curl -H "Content-Type: application/json" \
     -d '[{"id":1},{"id":2}]' https://api.example.com/batch

変数を含む JSON

変数を JSON 文字列へ埋め込むと、引用符や特殊文字で壊れます。安全なパターンは jq --arg/--argjson です — 有効な JSON を組み立て、値を正しくエスケープします。文字列には --arg、数値/真偽値には --argjson です。シークレットには、ps による漏洩を避けるため、コマンドライン引数よりヘッダーファイル(-H @file)を推奨します。

curl
# interpolate a shell variable into JSON (risky for special chars)
NAME="Alice"
curl -H "Content-Type: application/json" \
     -d "{\"name\":\"$NAME\"}" https://api.example.com

# safer: build JSON with jq
NAME="Alice"
jq -n --arg name "$NAME" '{name: $name}' | \
  curl -H "Content-Type: application/json" -d @- https://api.example.com

# multiple variables
NAME="Alice"; AGE=30
jq -n --arg name "$NAME" --argjson age "$AGE" \
  '{name: $name, age: $age}' | \
  curl -H "Content-Type: application/json" -d @- https://api.example.com

# read secret from env, hide from ps
TOKEN="$API_TOKEN" curl -H "Authorization: Bearer $API_TOKEN" \
     -d '{"x":1}' https://api.example.com

GraphQL リクエスト

GraphQL は 'query' 文字列と省略可能な 'variables' を含む JSON ボディで、単一の POST エンドポイントを使います。クエリをインラインで書くと内側のダブルクォートをエスケープする必要があるため、複雑なクエリは .json ファイルに保存し -d @file を使いましょう。イントロスペクション(__schema クエリ)が API の型を一覧し、探索に最適です。

curl
# GraphQL query as JSON body
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer TOKEN" \
     -d '{"query":"{ user(id:1) { name email } }"}' \
     https://api.example.com/graphql

# query with variables
curl -X POST \
     -H "Content-Type: application/json" \
     -d '{"query":"query($id:Int!){ user(id:$id){name} }","variables":{"id":1}}' \
     https://api.example.com/graphql

# query from a file (multi-line, no escaping pain)
curl -X POST \
     -H "Content-Type: application/json" \
     -d @query.json https://api.example.com/graphql

# introspection: list all types
curl -s -X POST -H "Content-Type: application/json" \
     -d '{"query":"{ __schema { types { name } } }"}' \
     https://api.example.com/graphql | jq

コンテンツネゴシエーション

Accept がレスポンス形式を交渉します。多くの REST API はデフォルトで JSON を返しますが、XML や CSV の代替をサポートします。--compressed は gzip/brotli を要求し自動で展開します。API はしばしば Accept 経由でバージョンを管理します(例:GitHub:application/vnd.github+json)。ネゴシエーションが機能したことを確認するには、サーバーが返す実際の Content-Type を確認しましょう。

curl
# request JSON
curl -H "Accept: application/json" https://api.example.com/users

# request XML
curl -H "Accept: application/xml" https://api.example.com/users

# request a specific version
curl -H "Accept: application/vnd.api+json; version=2" \
     https://api.example.com/users

# request anything (default is */*)
curl -H "Accept: */*" https://example.com

# request compression and auto-decompress
curl --compressed -H "Accept-Encoding: gzip, br" https://example.com

# inspect what the server actually returns
curl -s -o /dev/null -D - https://api.example.com/users | grep -i content-type
06

ファイルアップロード

マルチパートアップロード(-F)

-F(--form)は multipart/form-data リクエストを組み立てます — ファイルアップロードの標準です。-F file=@path でファイルを読み込みます。サーバーが見る名前の上書きには ;filename=、パートの Content-Type 設定には ;type= を加えましょう。同じフィールド名に複数のファイル(多くのフレームワークでは [] 付き)には、-F を複数回使います。

curl
# upload a file as a multipart form field
curl -F "[email protected]" https://api.example.com/upload

# -F sets POST + multipart/form-data automatically
# the @ prefix reads the file

# add a text field alongside the file
curl -F "[email protected]" -F "description=My photo" \
     https://api.example.com/upload

# rename the uploaded file (server sees "avatar.jpg")
curl -F "[email protected];filename=avatar.jpg" \
     https://api.example.com/upload

# set explicit content-type for the file part
curl -F "[email protected];type=image/jpeg" \
     https://api.example.com/upload

# upload multiple files in one field
curl -F "[email protected]" -F "[email protected]" \
     https://api.example.com/upload

複数ファイルとフィールド

マルチパートフォームはファイルとテキストフィールドを混ぜられます。配列形式のアップロードにはフィールド名に [] を使います(Rails/PHP などのフレームワークが配列としてパースします)。;type=application/json を設定すればフィールドは JSON を運べます — サーバーはファイルではなく構造化データとして読みます。curl はディレクトリをネイティブにアップロードできません。先に tar しましょう。

curl
# upload two files and a caption
curl -F "[email protected]" \
     -F "[email protected]" \
     -F "caption=Summer trip" \
     https://api.example.com/gallery

# array-style field names (PHP/Rails style)
curl -F "files[][email protected]" -F "files[][email protected]" \
     https://api.example.com/upload

# send a file's contents as a regular text field
curl -F "[email protected];type=application/json" \
     https://api.example.com/upload

# mix file and JSON fields
curl -F "[email protected]" \
     -F "options={\"priority\":\"high\"};type=application/json" \
     https://api.example.com/upload

# upload a directory as a tar (workaround)
tar -cf - mydir/ | curl -F "tar=@-;filename=dir.tar" \
     https://api.example.com/upload

ストリーミングアップロード(-T)

-T(--upload-file)は PUT を使いファイルをストリーミングするため、巨大なアップロードでもメモリはフラットです — 大きなデータでは -d @file よりはるかに優れています。-T - は stdin から読み込みます。-C - で中断された転送を再開します。URL の末尾にスラッシュがあると、curl はローカルのファイル名を追加します(HTTP PUT のミラーリングのように)。

curl
# upload a file with PUT (streaming, low memory)
curl -T localfile.txt https://example.com/upload/remote.txt

# upload to a URL with the local filename
curl -T localfile.txt https://example.com/upload/

# stream from stdin (pipe into PUT body)
cat data.json | curl -T - https://api.example.com/data

# upload with authentication
curl -T file.zip -u user:pass \
     https://example.com/upload/file.zip

# upload with progress bar
curl -T bigfile.iso --progress-bar \
     https://example.com/upload/bigfile.iso

# resume an interrupted upload
curl -T bigfile.iso -C - https://example.com/upload/bigfile.iso

進捗付きアップロード

デフォルトで curl は stderr に進捗メーターを表示します。--progress-bar でよりシンプルなバーに切り替わります。-s(silent)で隠れ、S を加える(-sS)とエラーは表示されたままです。進捗情報は stderr へ行くため、stdout(ボディ)はきれいなままです — パイプする際に有用です。1 行のサマリーには -w と %{size_upload}、%{time_total} を使いましょう。

curl
# default progress meter (terminal)
curl -T file.zip https://example.com/upload

# simple progress bar
curl -T file.zip --progress-bar https://example.com/upload

# no progress at all (silent)
curl -T file.zip -s https://example.com/upload

# show progress but only errors (silent + show-error)
curl -T file.zip -sS https://example.com/upload

# custom progress with --write-out
curl -T file.zip -w "Uploaded %{size_upload} bytes in %{time_total}s\n" \
     -o /dev/null https://example.com/upload

# redirect progress to stderr, body to file
curl -T file.zip --progress-bar 2> progress.log \
     -o response.txt https://example.com/upload

アップロードのフィールドとタイプ

curl は拡張子から MIME タイプを推測します。上書きには ;type= を使います。;filename= オプションはサーバーが見る名前を変えます — 無害化した名前に有用です。< 接頭辞はファイルの内容をテキストフィールドへ読み込みます(ファイルとして送るのではなく)— API が文字列を期待するのにデータがファイルにあるときに便利です。

curl
# specify MIME type explicitly
curl -F "[email protected];type=text/csv" https://api.example.com/import

# let curl guess from the extension (default)
curl -F "[email protected]" https://api.example.com/upload

# force generic type
curl -F "[email protected];type=application/octet-stream" \
     https://api.example.com/upload

# send a file with a custom filename visible to server
curl -F "upload=@/tmp/abc123;filename=report.pdf;type=application/pdf" \
     https://api.example.com/upload

# send a string as if it were a file
curl -F "file=hello world" https://api.example.com/upload

# send a string as a file with a filename
curl -F "file=<inline.txt" https://api.example.com/upload
07

認証

Basic 認証(-u)

-u(--user)は HTTP Basic 認証(base64 エンコードした user:pass)を送ります。パスワードを省略するとプロンプトが出ます(より安全 — シェルの履歴に残りません)。--netrc は ~/.netrc から認証情報を読み込み、コマンドラインには決して現れません。Basic は平文の HTTP では安全ではありません。必ず HTTPS を使いましょう。シェルアクセスを持つ人なら誰でも、ps で -u の引数が見えます。

curl
# HTTP Basic authentication
curl -u user:pass https://api.example.com/secret
curl --user user:pass https://api.example.com/secret

# prompt for password (don't put it on the command line)
curl -u user https://api.example.com/secret

# basic auth with explicit method (curl picks the safest by default)
curl -u user:pass --basic https://api.example.com/secret

# use a .netrc file instead of -u
echo "machine example.com login user password pass" > ~/.netrc
curl --netrc https://example.com/secret

# base64-encode credentials manually (equivalent)
curl -H "Authorization: Basic $(echo -n user:pass | base64)" \
     https://api.example.com/secret

Bearer トークン

Bearer トークン(OAuth2、JWT)は Authorization ヘッダーに入ります。トークンをコマンドラインに置くのは避けましょう — ps が他のユーザーに晒します。ファイルから読み込み(-H @file)、環境変数を使い、機密性の高い値にはヘッダーファイルを使いましょう。refresh-token のスニペットは標準的な OAuth2 クライアントクレデンシャルフローを示しています。

curl
# Bearer token (OAuth2 / JWT)
curl -H "Authorization: Bearer ACCESS_TOKEN" \
     https://api.example.com/protected

# token from an environment variable
curl -H "Authorization: Bearer $TOKEN" \
     https://api.example.com/protected

# token from a file (avoids shell history and ps)
curl -H "Authorization: Bearer $(cat ~/.token)" \
     https://api.example.com/protected

# headers from a file (cleanest for secrets)
echo "Authorization: Bearer $TOKEN" > /tmp/hdr.txt
curl -H @/tmp/hdr.txt https://api.example.com/protected
rm /tmp/hdr.txt

# refresh token flow (simplified)
TOKEN=$(curl -s -u client:secret -d "grant_type=refresh_token" \
        -d "refresh_token=$REFRESH" \
        https://auth.example.com/token | jq -r .access_token)
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/data

ヘッダーの API キー

API キーはカスタムヘッダー(X-API-Key、X-Client-Id)かクエリパラメータで現れます。クエリ文字列はサーバーのログやブラウザの履歴に漏れるため、ヘッダーを推奨します。AWS では --aws-sigv4 がアクセスキー/シークレットキーでリクエストに署名します。GitHub は個人アクセストークン(ghp_...)で Bearer を使います。

curl
# API key in a custom header (varies by service)
curl -H "X-API-Key: abc123" https://api.example.com/data

# API key as a query parameter
curl "https://api.example.com/data?api_key=abc123"

# GitHub personal access token
curl -H "Authorization: Bearer ghp_TOKEN" \
     https://api.github.com/user

# AWS-style signature v4 (use the AWS CLI or aws-sigv4)
curl --aws-sigv4 "aws:amz:us-east-1:service" \
     -u "ACCESS:SECRET" https://service.amazonaws.com/

# multiple keys
curl -H "X-API-Key: abc123" \
     -H "X-Client-Id: my-app" \
     https://api.example.com/data

Netrc ファイル

--netrc は ~/.netrc から認証情報を読み込み、ホストを login/password のペアへマッピングします。ファイルは chmod 600 でなければ curl は使用を拒否します。--netrc-file はカスタムの場所を指します。'default' エントリは特定の machine エントリのない任意のホストに適用されます。シークレットをコマンドラインから遠ざける最もきれいな方法です。

curl
# ~/.netrc stores credentials per host
# format:
#   machine api.example.com
#   login alice
#   password secret
#   machine github.com
#   login alice
#   password ghp_TOKEN

# use netrc automatically
curl --netrc https://api.example.com/data

# use a custom netrc file
curl --netrc-file ~/.netrc.work https://api.example.com/data

# ignore netrc for this request
curl --netrc-optional -u user:pass https://api.example.com/data

# secure the file (required by curl on some systems)
chmod 600 ~/.netrc

# machine + default for any host
# default
# login anonymous
# password guest

Digest と NTLM

Basic は認証情報を平文で送ります(HTTPS 上なら問題ありません)。Digest はハッシュを送り、パスワードは決して送りません。NTLM と Negotiate は Windows/Kerberos の SSO を扱います。--anyauth を付けると、サーバーの WWW-Authenticate ヘッダーに基づいて curl が選択します。サーバーがそのメソッドをサポートしている必要があり、-v でどのチャレンジが発行されたか分かります。

curl
# digest authentication (challenge-response, more secure than Basic)
curl -u user:pass --digest https://api.example.com/secret

# NTLM (Windows auth)
curl -u user:pass --ntlm https://intranet.example.com/

# negotiate (Kerberos/SPNEGO)
curl -u user:pass --negotiate https://intranet.example.com/

# anyauth: let curl pick the method
curl -u user:pass --anyauth https://api.example.com/secret

# specify the service principal for negotiate
curl -u user:pass --negotiate --service-name HTTP/intranet.example.com \
     https://intranet.example.com/

# show which method the server requested
curl -v -u user:pass --anyauth https://api.example.com 2>&1 | grep -i www-authenticate

OAuth とトークン

OAuth2 にはいくつかのグラントタイプがあります:client_credentials(サーバー間)、authorization_code(ブラウザログインの後)、password(レガシー)。トークンエンドポイントは access_token(多くの場合 refresh_token も)を返し、後続のリクエストでは access_token を Bearer ヘッダーとして使います。アプリパスワード(GitLab、GitHub)は -u で動き、2FA の制限をバイパスします。

curl
# OAuth2 client credentials grant
curl -u client_id:client_secret \
     -d "grant_type=client_credentials" \
     -d "scope=read write" \
     https://auth.example.com/oauth/token

# OAuth2 authorization code (after browser redirect)
curl -d "grant_type=authorization_code" \
     -d "code=AUTH_CODE" \
     -d "redirect_uri=https://app.example.com/callback" \
     -u client_id:client_secret \
     https://auth.example.com/oauth/token

# OAuth2 password grant (deprecated but still seen)
curl -d "grant_type=password" \
     -d "username=user" -d "password=pass" \
     -u client_id:client_secret \
     https://auth.example.com/oauth/token

# use the access token
curl -H "Authorization: Bearer $ACCESS_TOKEN" \
     https://api.example.com/me

# basic auth with username and app password (e.g., GitLab)
curl -u "user:app_password" https://gitlab.example.com/api/v4/user
08

Cookie

Cookie の送信(-b)

-b(--cookie)は Cookie を送ります。文字列ならそのまま送られ、ファイル名(Netscape 形式)なら保存された Cookie を読み込みます。複数の Cookie はセミコロン区切りです。-b は Cookie ヘッダーも設定します — -H 'Cookie: ...' と等価です。curl はデフォルトでは Set-Cookie をパースしないため、新しい Cookie を永続化するには -b を -c とペアにしましょう。

curl
# send a single cookie
curl -b "session=abc123" https://example.com/dashboard

# send multiple cookies
curl -b "session=abc123; theme=dark; lang=en" \
     https://example.com/dashboard

# send cookies from a file (Netscape format)
curl -b cookies.txt https://example.com/dashboard

# send a cookie with attributes (path, domain)
curl -b "session=abc123; Path=/; Domain=.example.com" \
     https://example.com/

# cookie via header (manual)
curl -H "Cookie: session=abc123; theme=dark" \
     https://example.com/dashboard

Cookie の保存(-c)

-c(--cookie-jar)は Set-Cookie レスポンスヘッダーを Netscape 形式のファイルへ書き込みます。読み込みの -b と書き込みの -c を同じファイルでペアにすれば、リクエストをまたいでセッションを維持できます:1 回ログインし、その後は認証付きの呼び出しでクッキージャーを再利用します。-c - で確認のために stdout へダンプします。

curl
# save response cookies to a file
curl -c cookies.txt https://example.com/login

# send and save cookies in one request
curl -b cookies.txt -c cookies.txt https://example.com/dashboard

# dump cookies to stdout (Netscape format)
curl -c - https://example.com/

# inspect cookies with --dump-header
curl -D headers.txt https://example.com/
grep -i set-cookie headers.txt

# login then reuse the session cookie
curl -c cookies.txt -d "user=alice&pass=secret" \
     https://example.com/login
curl -b cookies.txt https://example.com/dashboard

クッキージャー

クッキージャー(Netscape 形式)は curl の実行間で Cookie を永続化し、ブラウザのセッションを模倣します。-b と -c に同じジャーファイルを使えば、Cookie がリクエストごとに更新されます。形式はタブ区切りです:ドメイン、サブドメインを含むかのフラグ、パス、secure フラグ、有効期限(unix 時間)、名前、値。ログアウトするにはジャーを削除しましょう。

curl
# Netscape cookie file format:
# domain  flag  path  secure  expiration  name  value
# .example.com  TRUE  /  FALSE  1735689600  session  abc123

# full session: login, then call API with the same jar
JAR=/tmp/cookies.txt
curl -s -c "$JAR" -d "user=alice&pass=secret" https://example.com/login
curl -s -b "$JAR" https://example.com/api/profile
curl -s -b "$JAR" https://example.com/api/settings

# update the jar on every request (refresh expiring cookies)
curl -b "$JAR" -c "$JAR" https://example.com/api/data

# expire all cookies by deleting the jar
rm "$JAR"

# view the jar contents
cat "$JAR"
# or human-readable
curl -b "$JAR" -c - -o /dev/null https://example.com/

文字列からの Cookie

1 回限りのリクエストには、ジャーより文字列付きの -b が簡単です。Cookie はセミコロン区切りで、特殊文字を含む値は URL エンコードしましょう。Cookie ヘッダー(-H 経由)も等価で、ブラウザの Cookie 文字列をそのまま貼り付けられます — 取得したセッションのリプレイに有用です。

curl
# one-off cookie (no file)
curl -b "session=abc123" https://example.com/

# multiple cookies in one string
curl -b "session=abc123; theme=dark; lang=en" https://example.com/

# build cookie string from variables
SID="abc123"; THEME="dark"
curl -b "session=$SID; theme=$THEME" https://example.com/

# encode a value containing special chars
curl -b "data=$(python3 -c 'import urllib.parse;print(urllib.parse.quote("a&b"))')" \
     https://example.com/

# emulate a browser cookie header exactly
curl -H "Cookie: __cfduid=abc; _ga=GA1.2.xxx; session=xyz" \
     https://example.com/

セッション管理

Web のログインには、ログインページからの CSRF トークンと Cookie の永続化が必要なことが多いです。パターン:フォームを GET し(Cookie を保存)、トークンを取り出し、認証情報を POST し(Cookie + トークン付き)、その後は認証付きの呼び出しでジャーを再利用します。各リクエストがジャー(-c)を更新するため、更新されたセッション Cookie も伝播します。終わったら必ずログアウトしジャーを削除しましょう。

curl
# full login flow with cookie persistence
JAR=/tmp/session.txt

# 1. GET login page (capture CSRF token + cookies)
curl -s -c "$JAR" https://example.com/login > login.html
CSRF=$(grep csrf_token login.html | head -1 | grep -oP 'value="\K[^"]+')

# 2. POST credentials with CSRF and cookies
curl -s -b "$JAR" -c "$JAR" \
     -d "user=alice&pass=secret&csrf=$CSRF" \
     https://example.com/login

# 3. Access protected resources with the session
curl -s -b "$JAR" https://example.com/dashboard
curl -s -b "$JAR" https://example.com/api/data

# 4. Logout (invalidate session)
curl -s -b "$JAR" -c "$JAR" https://example.com/logout
rm "$JAR"
09

プロキシ

HTTP/HTTPS プロキシ

-x(--proxy)はリクエストをプロキシ経由にします。http_proxy/https_proxy/no_proxy 環境変数は自動的に尊重されます。HTTP プロキシ経由の HTTPS ターゲットには、curl は CONNECT でトンネルします。内部ホストのプロキシ回避には no_proxy を設定しましょう — カンマ区切りで、先頭のドットはサブドメインを意味します。

curl
# use a proxy for all requests
curl -x http://proxy.example.com:8080 https://example.com
curl --proxy http://proxy.example.com:8080 https://example.com

# HTTPS proxy (proxy connection itself is TLS)
curl -x https://proxy.example.com:8443 https://example.com

# proxy via environment variable
export https_proxy=http://proxy.example.com:8080
curl https://example.com

# proxy for a specific scheme only
curl --proxy http://proxy:8080 http://example.com
curl --proxy https://secure-proxy:8443 https://example.com

# bypass proxy for specific hosts
export no_proxy="localhost,127.0.0.1,.internal.example.com"
curl https://internal.example.com   # direct, no proxy

SOCKS プロキシ

SOCKS5 はプロトコルに依存しないため、HTTP、HTTPS など をトンネルします。--socks5-hostname はプロキシに DNS を解決させます(自分のマシンが解決できないホストに届くのに有用)。よくあるトリック:ssh -D 1080 でローカルの SOCKS プロキシを作り、リモートの SSH サーバー経由でトラフィックをトンネルします — 信頼できないネットワークでの安全な閲覧に最適です。

curl
# SOCKS5 proxy
curl -x socks5://proxy.example.com:1080 https://example.com
curl --socks5 proxy.example.com:1080 https://example.com

# SOCKS5 with local DNS resolution (server resolves)
curl --socks5-hostname proxy.example.com:1080 https://example.com

# SOCKS4 proxy
curl --socks4 proxy.example.com:1080 https://example.com

# SSH tunnel as a SOCKS proxy (run separately)
# ssh -D 1080 user@remote -N
curl -x socks5://localhost:1080 https://example.com

# SOCKS proxy with authentication
curl -x socks5://user:[email protected]:1080 https://example.com

プロキシ認証

プロキシは認証を要求することがよくあります。-U(--proxy-user)が認証情報を提供し、--proxy-ntlm/--proxy-digest/--proxy-anyauth が方式を選びます。-x の URL に user:pass を埋め込むのも等価です。NTLM(企業の Windows プロキシ)では --proxy-ntlm が多段階のハンドシェイクを処理します。-U user(パスワードなし)は対話的にプロンプトを出します。

curl
# proxy with username/password
curl -x http://user:[email protected]:8080 https://example.com

# separate proxy auth flag
curl -x http://proxy.example.com:8080 -U user:pass https://example.com
curl --proxy-user user:pass -x http://proxy.example.com:8080 https://example.com

# prompt for proxy password
curl -U user -x http://proxy.example.com:8080 https://example.com

# NTLM-authenticated proxy
curl -U user:pass --proxy-ntlm \
     -x http://proxy.example.com:8080 https://example.com

# digest-authenticated proxy
curl -U user:pass --proxy-digest \
     -x http://proxy.example.com:8080 https://example.com

# anyauth for proxy
curl -U user:pass --proxy-anyauth \
     -x http://proxy.example.com:8080 https://example.com

No Proxy とバイパス

--noproxy(または no_proxy 環境変数)はプロキシをバイパスするホストを列挙します。先頭のドットは「このドメインとすべてのサブドメイン」を意味し、'*' はすべてをバイパスします。CIDR の範囲は最近の curl で使えます。外部のプロキシが企業内部のホストに届かないときに不可欠です。

curl
# bypass proxy for specific hosts
curl --noproxy "localhost,127.0.0.1,.internal.com" \
     -x http://proxy:8080 https://example.com

# via environment variable
export no_proxy="localhost,127.0.0.1,.internal.com,10.0.0.0/8"
curl https://internal.com   # direct

# wildcard match for a domain and all subdomains
export no_proxy=".example.com"
curl https://api.example.com   # bypasses proxy

# disable proxy entirely for one request
curl --noproxy "*" -x http://proxy:8080 https://example.com

# ignore *_proxy env vars for one request
curl --noproxy "*" https://example.com

# CIDR ranges (curl 7.86+)
export no_proxy="192.168.0.0/16,10.0.0.0/8"

プロキシヘッダーとトンネリング

--proxy-header はプロキシ自身のためのヘッダー(Proxy-Authorization など)を加えます — ターゲットには転送されません。-p(--proxytunnel)は平文の HTTP でも CONNECT の使用を強制します(通常 CONNECT は HTTPS だけに使われる)。プロキシが平文 HTTP を傍受していて、エンドツーエンドのトンネルが欲しいときに有用です。

curl
# add a header sent only to the proxy (not the target)
curl -x http://proxy:8080 \
     --proxy-header "Proxy-Authorization: Bearer xyz" \
     https://example.com

# custom header to proxy + normal header to target
curl -x http://proxy:8080 \
     --proxy-header "X-Proxy-Tag: abc" \
     -H "X-Target-Tag: def" \
     https://example.com

# force CONNECT tunneling even for HTTP
curl -p -x http://proxy:8080 http://example.com
curl --proxytunnel -x http://proxy:8080 http://example.com

# inspect the CONNECT request to the proxy
curl -v -x http://proxy:8080 https://example.com 2>&1 | grep -i connect

# disable proxy tunneling (send HTTP directly through proxy)
curl --proxytunnel -p -x http://proxy:8080 http://example.com
10

SSL/TLS

検証のスキップ(--insecure)

-k(--insecure)は証明書の検証をスキップします — 自己署名の開発証明書のためだけに使い、本番では絶対に使わないでください。中間者(MITM)攻撃を許してしまいます。デフォルトでは証明書チェーンとホスト名の両方を検証します。--resolve で正しい Host/SNI を保ったまま IP を固定できます — ロードバランサーの後ろの特定のバックエンドのテストに有用です。

curl
# skip certificate verification (DANGEROUS)
curl -k https://self-signed.example.com
curl --insecure https://self-signed.example.com

# verify normally (default)
curl https://example.com

# show the cert chain
curl -v https://example.com 2>&1 | grep -E "SSL|cert"

# only verify the cert, not the hostname
curl --insecure https://example.com   # both off
# (no built-in flag to verify cert but skip hostname;
#  use a custom CA bundle instead)

# connect to a host with a mismatched certificate
curl -k --resolve example.com:443:1.2.3.4 https://example.com

# debug TLS handshake
curl -v https://example.com 2>&1 | grep -E "TLS|SSL|cert|cipher"

クライアント証明書

相互 TLS(mTLS)にはクライアント証明書(--cert)とその秘密鍵(--key)の両方が必要です。PEM がデフォルトで、--cert-type P12 が PKCS#12 バンドルを扱います。--pass が鍵のパスワードを提供します。--cacert は信頼する CA のリストを上書きします(デフォルト:システムストア)— 内部 CA に有用です。mTLS はゼロトラストやサービスメッシュの構成で一般的です。

curl
# client certificate + private key (mTLS)
curl --cert client.pem --key client.key \
     https://mtls.example.com/api

# PKCS#12 bundle (combined cert + key)
curl --cert client.p12 --cert-type P12 \
     https://mtls.example.com/api

# password-protected key
curl --cert client.pem --key client.key \
     --pass secret https://mtls.example.com/api

# PEM cert with password
curl --cert client.pem:secret https://mtls.example.com/api

# specify CA bundle to verify the server
curl --cacert custom-ca.pem https://internal.example.com

# mutual TLS with custom CA
curl --cert client.pem --key client.key \
     --cacert internal-ca.pem \
     https://mtls.internal.example.com

TLS バージョン

--tlsv1.X が最低バージョンを設定し、--tls-max が上限を設定します。1.2 以上を強制すると、既知の弱点を持つレガシープロトコル(SSLv3、TLS 1.0/1.1)が無効になります。デフォルトでは互いにサポートする最も高いバージョンを交渉します。-v で「SSL connection using」の行から交渉されたバージョンと暗号が分かります。

curl
# force a minimum TLS version
curl --tlsv1.2 https://example.com
curl --tlsv1.3 https://example.com

# force an exact TLS version
curl --tls-max 1.2 https://example.com   # cap at 1.2
curl --tls-max 1.3 https://example.com

# negotiate the highest version both support (default)
curl https://example.com

# disable specific versions
curl --tlsv1.2 --tls-max 1.2 https://example.com   # only 1.2

# list versions curl supports
curl --version | grep -i tls

# debug which version was negotiated
curl -v https://example.com 2>&1 | grep -i "SSL connection"

暗号と CA バンドル

--ciphers は暗号スイートを制限します(OpenSSL 構文)。--cacert は内部/プライベート CA を持つサーバーの検証用にカスタム CA バンドルを指します — デフォルトではシステムのバンドル(/etc/ssl/certs や macOS キーチェーン)が使われます。CA バンドルが古いと、有効な証明書を持つサーバーが拒否されることがあります。curl(または ca-certificates パッケージ)の更新で解決します。

curl
# specify allowed ciphers
curl --ciphers "AES256-GCM-SHA384:AES128-GCM-SHA256" \
     https://example.com

# use a custom CA bundle to verify the server
curl --cacert /etc/ssl/certs/internal-ca.pem \
     https://internal.example.com

# use the system CA store (default)
curl https://example.com

# use Mozilla's CA bundle (download separately)
curl --cacert cacert.pem https://example.com

# show the cipher used
curl -v https://example.com 2>&1 | grep -i cipher

# disable certificate revocation checks (CRL/OCSP)
curl --cacert ca.pem --no-clobber https://example.com

証明書の検査

-v でサーバーの証明書(subject、issuer、有効期間)を検査できます。--pinnedpubkey は証明書ピンニングを強制します — サーバーの公開鍵が一致しないとリクエストが失敗し、不正な CA にも耐えます。深い TLS デバッグには --trace-ascii がハンドシェイク全体をダンプします。証明書検査には openssl s_client がより強力な代替です。

curl
# show the server certificate in verbose mode
curl -v https://example.com 2>&1 | grep -A1 "server certificate"

# extract certificate details (subject, issuer, dates)
curl -v https://example.com 2>&1 | grep -E "subject|issuer|start date|expire date"

# download the server certificate (PEM)
curl -v https://example.com 2>&1 | \
  awk '/-----BEGIN CERT/,/-----END CERT/' > server.pem

# verify cert only, don't transfer body
curl -I https://example.com

# pin a specific certificate (fingerprint)
curl --pinnedpubkey sha256//BASE64= https://example.com

# check OCSP stapling
curl -v https://example.com 2>&1 | grep -i ocsp

# show full TLS trace
curl --trace-ascii - https://example.com | grep -i cert
11

ダウンロード

ファイルへの保存(-o/-O)

-o は指定したファイル名へ書き込み、-O はリモートのファイル名(URL の basename)を使います。--output-dir が -O の保存先フォルダを設定します。複数の -O フラグで 1 回の実行で複数のファイルをダウンロードします。-o /dev/null はボディを破棄します — データを保存せずに Webhook を発火させたり、時間を測るのに有用です。

curl
# save with a custom name
curl -o page.html https://example.com/index.html

# save with the remote filename
curl -O https://example.com/file.zip

# save to a specific directory
curl -O --output-dir /tmp/downloads https://example.com/file.zip

# save with remote name to a specific dir
curl -o /tmp/file.zip https://example.com/file.zip

# download multiple files with remote names
curl -O https://example.com/a.zip -O https://example.com/b.zip

# save to /dev/null (just trigger the request)
curl -o /dev/null https://example.com/webhook

ダウンロードの再開(-C)

-C -(--continue-at -)は既存のファイルサイズをバイトオフセットとして、中断した所からダウンロードを再開します。サーバーが Range リクエストをサポートしている必要があります(Accept-Ranges: bytes を確認)。不安定な接続への対処には --retry と組み合わせましょう — curl が再試行と再開を行い、帯域の無駄を避けます。

curl
# resume a partial download
curl -C - -o file.zip https://example.com/file.zip
curl --continue-at - -o file.zip https://example.com/file.zip

# resume with -O (remote name)
curl -C - -O https://example.com/file.zip

# start download at a specific byte offset
curl -C 1024 -o file.zip https://example.com/file.zip

# server must support Range requests
curl -I https://example.com/file.zip | grep -i accept-ranges

# resume an interrupted large download
curl -C - --progress-bar -O https://example.com/bigfile.iso

# combine with retry for unreliable connections
curl -C - --retry 5 --retry-all-errors -O \
     https://example.com/bigfile.iso

プログレスバー

--progress-bar はデフォルトのメーターではなく、よりシンプルな ### のバーを表示します。-s ですべての進捗が消え、-sS ならエラーは残ります。進捗は stderr へ行くため、stdout のボディを汚しません — 両方を別々に取り込めます。-w と %{size_download}、%{time_total} で、スクリプト用のきれいな 1 行サマリーが得られます。

curl
# default progress meter
curl -O https://example.com/file.zip

# simple progress bar (alternative style)
curl --progress-bar -O https://example.com/file.zip

# silent (no progress, no body output)
curl -s -O https://example.com/file.zip

# silent but still show errors
curl -sS -O https://example.com/file.zip

# show only errors (no progress, body to file)
curl -sS -o file.zip https://example.com/file.zip

# custom one-line progress
curl -o file.zip -w "%{size_download} bytes in %{time_total}s\n" \
     https://example.com/file.zip

# redirect progress to a file, body to another
curl -o file.zip --progress-bar 2> progress.log \
     https://example.com/file.zip

ダウンロードの範囲

-r(--range)はバイト範囲を要求し、206 Partial Content が返ります。大きなファイルのプレビュー、再開、並列の複数接続ダウンロードに有用です。サーバーが Accept-Ranges: bytes を宣伝している必要があります。シェルのバックグラウンド(&)と組み合わせれば範囲を同時にダウンロードし、後で結合できます — aria2 のようなダウンロードアクセラレータの基礎です。

curl
# download bytes 0-1023 (first 1KB)
curl -r 0-1023 -o part1.bin https://example.com/file.zip

# download from byte 1024 to end
curl -r 1024- -o rest.bin https://example.com/file.zip

# download last 500 bytes
curl -r -500 -o tail.bin https://example.com/file.zip

# check if server supports ranges
curl -I https://example.com/file.zip | grep -i accept-ranges
# Accept-Ranges: bytes  -> supported

# parallel range download (split a large file)
curl -r 0-49999999    -o part1.bin https://example.com/big.iso &
curl -r 50000000-99999999 -o part2.bin https://example.com/big.iso &
wait
cat part1.bin part2.bin > big.iso

# HTTP/1.1 206 Partial Content confirms success
curl -r 0-100 -v https://example.com/file.zip 2>&1 | grep HTTP

複数ファイルとグロビング

URL グロビング([1-3]、{a,b,c})は展開ごとに 1 リクエストを発行します。--output-dir が -O の保存先を設定します。真の並列性(curl 自体は逐次)のためには、URL を xargs -P N にパイプして N 個の curl を同時に動かしましょう。同じホストから多くの小さなファイルをダウンロードするとき、劇的に高速化します(サーバーのレート制限は尊重しましょう)。

curl
# download file1.zip, file2.zip, file3.zip
curl -O https://example.com/file[1-3].zip

# download with a step (1, 3, 5, 7, 9)
curl -O https://example.com/file[1-9:2].zip

# download from multiple paths
curl -O https://example.com/{a,b,c}.zip

# download to a specific directory
curl -O --output-dir /tmp/downloads \
     https://example.com/file[1-3].zip

# sequential download (one at a time)
for url in https://example.com/{a,b,c}.zip; do
  curl -O "$url"
done

# parallel download with xargs
echo "https://example.com/{a,b,c}.zip" | tr ' ' '\n' | \
  xargs -n1 -P3 curl -O

ミラーと再帰

curl は設計上単一 URL です — 再帰しません。サイトをミラーするには wget --mirror を使うか、grep でリンク抽出をスクリプト化しましょう。バッチダウンロードには、URL をファイルに列挙し、xargs -P N で並列化します。sitemap の例は、サイトがインデックスしたすべてのページを取得してダウンロードします — オフラインスナップショットに便利です。

curl
# curl doesn't recurse like wget, but you can script it
# download a page and extract its links
curl -s https://example.com/ | \
  grep -oP 'href="\K[^"]+' | grep '^http' > urls.txt

# download all linked PDFs
curl -s https://example.com/docs | \
  grep -oP 'href="\K[^"]+\.pdf' | \
  while read pdf; do curl -O "https://example.com/$pdf"; done

# use wget instead for true mirroring
# wget --mirror --convert-links --page-requisites https://example.com/

# download a list of URLs from a file
xargs -n1 -P4 curl -O < urls.txt

# fetch a sitemap and download every URL
curl -s https://example.com/sitemap.xml | \
  grep -oP '<loc>\K[^<]+' | xargs -n1 -P4 curl -O
12

タイムアウトとリトライ

接続タイムアウト

--connect-timeout は TCP/TLS 接続の確立時間を上限とします(転送ではありません)。なければ、curl は到達不能なホストで数分間ハングすることがあります(OS のデフォルトは約 2 分)。スクリプトでは、ハングを避けるため --connect-timeout(死んだホストで早く失敗)と --max-time(操作全体の上限)の両方を常に設定しましょう。

curl
# max time to establish the connection (seconds)
curl --connect-timeout 10 https://example.com

# connect timeout in milliseconds (curl 7.32+)
curl --connect-timeout 2.5 https://example.com

# connect timeout + overall max time
curl --connect-timeout 10 --max-time 30 https://example.com

# DNS resolution timeout (curl 7.88+, otherwise OS-controlled)
curl --happy-eyeballs-timeout-ms 1000 https://example.com

# fail fast on unreachable hosts
curl --connect-timeout 3 -sS https://example.com || echo "unreachable"

# combine with --retry for resilience
curl --connect-timeout 5 --max-time 20 --retry 3 \
     https://example.com

最大時間

--max-time(-m)は操作全体(DNS + 接続 + 転送)を上限とします。--speed-time/--speed-limit は転送速度が一定時間しきい値を下回ると中断します — 止まったダウンロードに最適です。終了コード 28 がタイムアウトを意味するため、スクリプトでは $? を確認しましょう。遅い・詰まったサーバーでの無限ハングを防ぐため、必ず max-time を設定しましょう。

curl
# overall timeout for the whole operation
curl --max-time 30 https://example.com
curl -m 30 https://example.com

# max time in milliseconds (decimal)
curl --max-time 2.5 https://example.com

# max time with no data transfer (idle timeout)
curl --speed-time 30 --speed-limit 1000 https://example.com
# abort if speed < 1000 bytes/sec for 30 sec

# max time for a file upload
curl -T big.iso --max-time 600 https://example.com/upload

# max time per redirect hop
curl -L --max-time 60 https://example.com/redirect

# check exit code (28 = timed out)
curl --max-time 5 https://slow.example.com || echo "exit code: $?"

リトライ

--retry は一時的なエラー(タイムアウト、5xx、429)でデフォルトで再試行し、--retry-all-errors ですべての失敗へ拡張します。--retry-delay は再試行間に固定の待ちを加えます(試行ごとに倍増)。--retry-connrefused は接続が拒否されても再試行します(サーバー再起動中など)。部分的なダウンロードの再開には -C - とペアにしましょう。耐障害性のあるスクリプトには不可欠です。

curl
# retry up to 3 times on transient errors
curl --retry 3 https://example.com

# retry on any error (not just transient)
curl --retry 3 --retry-all-errors https://example.com

# retry with exponential backoff
curl --retry 5 --retry-delay 2 https://example.com
# waits 2s, 4s, 6s, 8s, 10s between retries (curl 7.66+)

# retry on connection-refused specifically
curl --retry 3 --retry-connrefused https://example.com

# retry only on HTTP 5xx and 429
curl --retry 3 --retry-all-errors \
     -H "Accept: application/json" https://api.example.com

# combine with resume for large downloads
curl --retry 5 --retry-all-errors -C - -O \
     https://example.com/bigfile.iso

リトライの遅延とバックオフ

--retry-delay N は最初の再試行の前に N 秒待ち、その後倍増します(N、2N、4N...)。curl は 429/503 レスポンスでサーバーの Retry-After ヘッダーを尊重します。カスタムロジック(ジッター、最大合計待ち時間、ステータスコードでの条件分岐)には、curl をシェルループで包みましょう。再試行が永遠に走らないよう、--retry には必ず --max-time をペアにしましょう。

curl
# fixed delay between retries
curl --retry 5 --retry-delay 2 https://example.com

# exponential backoff (curl doubles the delay each time)
curl --retry 5 --retry-delay 1 https://example.com
# waits: 1s, 2s, 4s, 8s, 16s

# honor Retry-After header (default with --retry)
curl --retry 3 https://example.com

# cap retry delay with a max-time
curl --retry 10 --retry-delay 1 --max-time 60 https://example.com

# custom backoff in a shell loop
for i in 1 2 3 4 5; do
  curl -s --max-time 10 https://example.com && break
  echo "attempt $i failed, waiting $((i*2))s..."
  sleep $((i*2))
done

# retry on specific HTTP status codes
curl --retry 5 --retry-all-errors \
     -w "%{http_code}" -o /dev/null -s https://example.com

速度の制限

--speed-time/--speed-limit は詰まった転送を中断します(しきい値未満の速度で N 秒間データなし)— 終了コード 28。--limit-rate は転送レートを上限とします(K/M/G 接尾辞に対応)— 帯域を飽和させないためや、遅いネットワークのテストに有用です。詰まったダウンロードを自動で再開するには --retry と組み合わせましょう。

curl
# abort if speed drops below 1000 bytes/sec for 30 sec
curl --speed-limit 1000 --speed-time 30 -O \
     https://example.com/bigfile.iso

# shorthand: --speed-time defaults to 30 if only --speed-limit is set
curl --speed-limit 1000 -O https://example.com/bigfile.iso

# limit max download rate (bytes/sec)
curl --limit-rate 100k -O https://example.com/file.zip

# limit rate with units (K, M, G)
curl --limit-rate 1M -O https://example.com/file.zip

# limit upload rate
curl -T big.iso --limit-rate 500k https://example.com/upload

# combine with retry on stall
curl --speed-limit 1000 --speed-time 30 \
     --retry 5 --retry-all-errors \
     -O https://example.com/bigfile.iso
13

デバッグ

詳細出力(-v)

-v(verbose)が主要なデバッグツールです。'>' の行がリクエスト、'<' の行がレスポンス、'*' の行が curl の内部(DNS、TLS、接続)— すべて stderr 上にあり、stdout はボディ用にきれいなままです。2>&1 でリダイレクトして grep でフィルタしましょう。-o /dev/null でボディを保存せずにヘッダーを確認できます。

curl
# verbose: full request + response + curl internals
curl -v https://example.com

# output goes to stderr; body to stdout
curl -v https://example.com > body.txt 2> debug.log

# only show request headers (> lines)
curl -v https://example.com 2>&1 | grep '^>'

# only show response headers (< lines)
curl -v https://example.com 2>&1 | grep '^<'

# only show curl info (* lines)
curl -v https://example.com 2>&1 | grep '^\*'

# verbose without sending the body
curl -v -o /dev/null https://example.com

Trace

--trace はすべて(ボディを含む)を hex + ASCII でダンプし、--trace-ascii は hex を省きます。--trace-time でタイムスタンプが加わります。-v と違い、trace はリクエストとレスポンスのボディを表示するため、バイナリや圧縮データのデバッグの頼みの綱です。警告:--trace はシークレット(パスワード、トークン)を記録します — 共有する前に清掃しましょう。

curl
# trace: dump all sent and received data (hex + ASCII)
curl --trace - https://example.com

# trace ASCII only (no hex dump)
curl --trace-ascii - https://example.com

# trace to a file
curl --trace trace.log https://example.com

# trace including time per packet
curl --trace-ascii - --trace-time https://example.com

# trace with request body (hidden by default in -v)
curl --trace-ascii - -d "secret=data" https://example.com

# compare verbose vs trace
curl -v https://example.com 2>&1 | head
curl --trace-ascii - https://example.com | head

ヘッダーのみ

-I は HEAD リクエストを送ります(多くのサーバーはボディなしの GET と同じヘッダーを返します)。-D はヘッダーをファイルか '-'(stdout)へダンプします。curl が送ったもの(リクエストヘッダー)を見るには、-v と grep '^>' を使います。ステータスコードだけなら、-w '%{http_code}' が最もきれいです。注意:HEAD と GET で異なるレスポンスを返すサーバーもあります。

curl
# HEAD request: response headers only
curl -I https://example.com
curl --head https://example.com

# dump response headers to stdout, discard body
curl -D - -o /dev/null https://example.com

# dump response headers to a file
curl -D headers.txt -o body.html https://example.com

# show request headers (what curl sent)
curl -v -o /dev/null https://example.com 2>&1 | grep '^>'

# show both request and response headers
curl -v -o /dev/null https://example.com 2>&1 | grep -E '^[<>]'

# show only the status line
curl -s -o /dev/null -w "%{http_code} %{http_version}\n" \
     https://example.com
curl -D - -o /dev/null -s https://example.com | head -1

リクエストとレスポンスの分離

詳細出力は stderr へ、ボディは stdout へ行くため、リダイレクトで別々に取り込めます。-D がレスポンスヘッダーを保存し、-o がボディを保存し、-v(stderr)がやり取り全体を取り込みます。この分離は API のデバッグに不可欠です:ヘッダーとボディを独立に検査し、時間を記録し、リクエストとレスポンスを比較しましょう。

curl
# capture request and response separately
curl -v https://example.com \
     -o body.txt \
     1> /dev/null 2> verbose.log

# extract request only
curl -v https://example.com 2>&1 1>/dev/null | grep '^>' > request.txt

# extract response only
curl -v https://example.com 2>&1 1>/dev/null | grep '^<' > response.txt

# split headers and body cleanly
curl -s -D headers.txt -o body.txt https://example.com

# capture everything: body, headers, request, timing
curl -s -D headers.txt -o body.txt \
     -w "@curl-format.txt" https://example.com >> timing.log

# show body to terminal, headers to file
curl -D headers.txt https://example.com

デバッグオプション

--dry-run は送信せずに curl がやることを表示します — URL グロビングや設定の検証に最適です。--resolve はホストを IP に固定し DNS をバイパスします(特定のバックエンドのテストに不可欠)。--interface はネットワークカードか IP に束縛します。--no-keepalive はリクエストごとに新しい接続を強制し、接続レベルのバグの再現に有用です。

curl
# show what curl would do without sending
curl --dry-run https://example.com

# dump parsed config files
curl --config /dev/null -v https://example.com 2>&1 | grep -i config

# force a fresh connection (no keep-alive reuse)
curl --no-keepalive https://example.com

# disable DNS cache
curl --doh-url https://dns.example.com/dns-query https://example.com

# use a specific network interface
curl --interface eth0 https://example.com
curl --interface 192.168.1.5 https://example.com

# resolve a hostname to a specific IP (no DNS)
curl --resolve example.com:443:1.2.3.4 https://example.com

# debug globbing (list URLs without fetching)
curl --dry-run -O https://example.com/file[1-3].zip
14

レスポンス情報

HTTP ステータスコード

-w '%{http_code}' はスクリプティング用にステータスコードだけを取り出します。-f(--fail)は 4xx/5xx で非ゼロで終了させます(なければ curl は 404 でも 0 を返します)。--fail-with-body はエラー時にもレスポンスボディを表示します(デバッグに有用)。ステータスコードでスクリプトを分岐させましょう:2xx 成功、3xx リダイレクト、4xx クライアントエラー、5xx サーバーエラー。

curl
# get only the status code
curl -s -o /dev/null -w "%{http_code}" https://example.com
echo   # 200

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

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

# branch on status code
CODE=$(curl -s -o /dev/null -w "%{http_code}" https://example.com)
if [ "$CODE" = "200" ]; then echo "ok"; else echo "fail: $CODE"; fi

# fail on HTTP errors (4xx, 5xx)
curl -f https://example.com || echo "HTTP error"
curl --fail-with-body https://example.com   # 7.76+: still print body

# check redirect chain status codes
curl -L -w "%{num_redirects} redirects, final %{http_code}\n" \
     -o /dev/null -s https://short.url/abc

Write-out 形式

-w(--write-out)は %{variable} プレースホルダーで転送情報を整形します。タイミング(time_namelookup、time_connect、time_appconnect、time_total)は時間の行き先を分解します — パフォーマンス分析に不可欠です。%{json} がすべての変数を JSON で出力します(curl 7.70+)。形式をファイルに保存し、-w @file で再利用しましょう。

curl
# built-in variables with -w / --write-out
curl -s -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" \
     https://example.com

# URL info
curl -s -o /dev/null -w "URL: %{url_effective}\nIP: %{remote_ip}\n" \
     https://example.com

# timing breakdown
curl -s -o /dev/null \
     -w "dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} total=%{time_total}\n" \
     https://example.com

# size info
curl -s -o /dev/null \
     -w "downloaded=%{size_download} uploaded=%{size_upload}\n" \
     https://example.com

# write format from a file
cat > fmt.txt <<EOF
http_code: %{http_code}
time_total: %{time_total}s
EOF
curl -s -o /dev/null -w "@fmt.txt" https://example.com

# JSON output (curl 7.70+)
curl -s -o /dev/null -w "%{json}" https://example.com

レスポンスタイム

タイミング変数はリクエストを分解します:time_namelookup(DNS)、time_connect(TCP)、time_appconnect(TLS)、time_starttransfer(TTFB — 最初のバイトを受信)、time_total(転送全体)。TTFB が API レイテンシの重要な指標です。エンドポイント間でタイミングを比較すれば、ボトルネック(DNS、ネットワーク、TLS、サーバー処理)を特定できます。

curl
# total time
curl -s -o /dev/null -w "%{time_total}\n" https://example.com

# DNS resolution time
curl -s -o /dev/null -w "%{time_namelookup}\n" https://example.com

# TCP connect time
curl -s -o /dev/null -w "%{time_connect}\n" https://example.com

# TLS handshake time (after connect)
curl -s -o /dev/null -w "%{time_appconnect}\n" https://example.com

# time to first byte (TTFB)
curl -s -o /dev/null -w "%{time_starttransfer}\n" https://example.com

# full timing breakdown
curl -s -o /dev/null -w \
  "dns=%{time_namelookup} tcp=%{time_connect} tls=%{time_appconnect} ttfb=%{time_starttransfer} total=%{time_total}\n" \
  https://example.com

# compare two endpoints
curl -s -o /dev/null -w "%{time_total}\n" https://api1.example.com
curl -s -o /dev/null -w "%{time_total}\n" https://api2.example.com

ヘッダーの抽出

-D - はレスポンスヘッダーを stdout へダンプし、grep にパイプして特定のヘッダーを取り出せます。-I(HEAD)も機能しますが GET と異なることがあります。-w は %{url_effective}(リダイレクト後の最終 URL)、%{remote_ip}(サーバー IP)、%{num_redirects} を提供します。CDN ルーティング、リダイレクト、サーバー特定のデバッグに非常に有用です。

curl
# dump all response headers to stdout, discard body
curl -s -D - -o /dev/null https://example.com

# extract one header (Content-Type)
curl -s -D - -o /dev/null https://example.com | \
  grep -i "^content-type:"

# extract Content-Length (size)
curl -s -I https://example.com/file.zip | grep -i content-length

# extract Set-Cookie
curl -s -D - -o /dev/null https://example.com | grep -i set-cookie

# extract the final URL after redirects
curl -s -L -o /dev/null -w "%{url_effective}\n" https://short.url/abc

# extract the server's IP address
curl -s -o /dev/null -w "%{remote_ip}\n" https://example.com

# count redirects
curl -s -L -o /dev/null -w "%{num_redirects}\n" https://short.url/abc

形式変数

-w(--write-out)は数十の変数をサポートします('curl -w "%{json}"' を実行すれば全部が JSON で見えます)。タイミング変数がパフォーマンス監視の基礎で、サイズ変数が帯域を追跡し、url_effective と num_redirects がルーティングをデバッグします。%{json}(curl 7.70+)が、ロギングやダッシュボード用にすべてを取り込む最も簡単な方法です。

curl
# complete list of common -w variables
# %{http_code}        - response status code
# %{http_version}     - HTTP version (1.1, 2, 3)
# %{url_effective}    - final URL after redirects
# %{remote_ip}        - server IP address
# %{remote_port}      - server port
# %{time_namelookup}  - DNS resolution time
# %{time_connect}     - TCP connect time
# %{time_appconnect}  - TLS handshake time
# %{time_pretransfer} - time before transfer starts
# %{time_starttransfer} - TTFB (first byte)
# %{time_total}       - total time
# %{size_download}    - bytes downloaded
# %{size_upload}      - bytes uploaded
# %{size_header}      - header bytes
# %{size_request}     - request bytes
# %{num_redirects}    - number of redirects
# %{ssl_verify_result}- SSL verification result
# %{content_type}     - response content type
# %{json}             - all variables as JSON (7.70+)

# reference: curl -w "%{json}" https://example.com
curl -s -o /dev/null -w "%{json}" https://example.com | jq
15

FTP と SMTP

FTP の基本

curl は FTP のダウンロード(GET)とアップロード(-T 経由の PUT)の両方に対応します。-u が認証情報を提供し、匿名 FTP は 'anonymous' + メールアドレスです。FTPS(--ftp-ssl)は制御チャネルを暗号化します。パッシブモード(デフォルト)は NAT/ファイアウォールを通して動き、サーバーが要求するならアクティブモードに --ftp-port を使いましょう。

curl
# anonymous FTP download
curl ftp://ftp.example.com/file.txt

# authenticated FTP
curl -u user:pass ftp://ftp.example.com/file.txt

# list a directory
curl ftp://ftp.example.com/directory/

# download a file
curl -O ftp://ftp.example.com/file.txt

# upload a file (PUT)
curl -T local.txt ftp://ftp.example.com/remote.txt -u user:pass

# use explicit FTPS (FTP over TLS)
curl --ftp-ssl ftp://ftp.example.com/file.txt -u user:pass

# passive mode (default; needed behind NAT/firewalls)
curl --ftp-pasv ftp://ftp.example.com/ -u user:pass

FTP アップロード

-T は FTP の STOR コマンドでファイルをアップロードします。--ftp-create-dirs は MKD で親ディレクトリを作ります。--append は APPE で既存のファイルに追記します。-C - で中断されたアップロードを再開します。グロビング({a,b})で 1 回の実行で複数のファイルをアップロードできます。ディレクトリは先に tar しましょう — FTP はフォルダを直接アップロードできません。

curl
# upload a single file
curl -T local.txt ftp://ftp.example.com/remote.txt -u user:pass

# upload with explicit filename
curl -T local.txt -o remote.txt ftp://ftp.example.com/ -u user:pass

# upload to a directory
curl -T local.txt ftp://ftp.example.com/uploads/ -u user:pass

# create a directory (MKD command)
curl --ftp-create-dirs -T local.txt \
     ftp://ftp.example.com/newdir/file.txt -u user:pass

# append to a remote file
curl -T local.txt --append ftp://ftp.example.com/remote.txt -u user:pass

# upload multiple files with globbing
curl -T "{file1,file2}.txt" ftp://ftp.example.com/ -u user:pass

# resume an interrupted upload
curl -C - -T bigfile.iso ftp://ftp.example.com/bigfile.iso -u user:pass

FTP の一覧

スラッシュで終わる FTP URL はディレクトリを一覧します。--list-only はファイル名だけを返します。-v で背後の FTP コマンド(USER、PASS、PASV、LIST、RETR)が見えます — 権限やファイアウォールの問題のデバッグに非常に有用です。curl はサブディレクトリへ再帰できません。再帰的な FTP ダウンロードには wget --mirror かスクリプトを使いましょう。

curl
# list a directory (default format)
curl ftp://ftp.example.com/ -u user:pass

# list with --list-only (names only, no details)
curl --list-only ftp://ftp.example.com/ -u user:pass

# list a specific directory
curl ftp://ftp.example.com/pub/ -u user:pass

# recursive listing (curl doesn't recurse natively)
# use --ftp-method to control PASV/EPSV behavior
curl --ftp-method nocwd ftp://ftp.example.com/ -u user:pass

# download all files in a directory (with globbing)
curl -O ftp://ftp.example.com/pub/*.txt -u user:pass

# show server responses (FTP commands)
curl -v ftp://ftp.example.com/ -u user:pass 2>&1 | grep -E "^\*|^[<>]"

SMTP メール送信

curl は SMTP 経由でメールを送れます。ボディ(ヘッダーを含む)は -T でパイプされるファイルにあります。--mail-from と --mail-rcpt がエンベロープを設定します(ボディ内の To/From ヘッダーとは別)。--ssl-reqd が STARTTLS を強制し(ポート 587)、smtps:// は暗黙 TLS を使います(ポート 465)。認証は -u(LOGIN/PLAIN)です。メールクライアントのないサーバーからのスクリプト化されたアラートに最適です。

curl
# send email via SMTP
curl --url "smtp://smtp.example.com:587" \
     --mail-from "[email protected]" \
     --mail-rcpt "[email protected]" \
     -u "[email protected]:password" \
     -T email.txt

# email body from a file
cat > email.txt <<EOF
From: [email protected]
To: [email protected]
Subject: Test from curl

Hello from curl!
EOF
curl --url "smtp://smtp.example.com:587" \
     --mail-from "[email protected]" \
     --mail-rcpt "[email protected]" \
     -u "[email protected]:password" \
     --ssl-reqd \
     -T email.txt

# multiple recipients
curl --url "smtp://smtp.example.com:587" \
     --mail-from "[email protected]" \
     --mail-rcpt "[email protected]" \
     --mail-rcpt "[email protected]" \
     -T email.txt

# STARTTLS (port 587)
curl --ssl-reqd --url "smtp://smtp.example.com:587" \
     --mail-from "[email protected]" --mail-rcpt "[email protected]" \
     -T email.txt

# SMTPS (implicit TLS, port 465)
curl --url "smtps://smtp.example.com:465" \
     --mail-from "[email protected]" --mail-rcpt "[email protected]" \
     -T email.txt

IMAP と POP3

curl は IMAP と POP3 経由でメールを読めます。URL 構文にはフォルダ、UID、セクションセレクタが含まれます。IMAP は検索に対応しています(?UNSEEN、?SUBJECT など)。imaps:// と pop3s:// は暗黙 TLS を使います。注意:メールに対する curl は読み取り専用です — IMAP/POP3 では取得できても送信はできません(送信には SMTP を使いましょう)。ボディは生の RFC 822 メッセージテキストとして返されます。

curl
# list IMAP mailboxes
curl -u "user:pass" --url "imap://imap.example.com:143"

# list messages in INBOX
curl -u "user:pass" --url "imap://imap.example.com/INBOX"

# fetch a specific message (UID 1)
curl -u "user:pass" --url "imap://imap.example.com/INBOX;UID=1"

# fetch message headers only
curl -u "user:pass" --url "imap://imap.example.com/INBOX;UID=1;SECTION=HEADER"

# search for unread messages
curl -u "user:pass" --url "imap://imap.example.com/INBOX?UNSEEN"

# POP3: list messages
curl -u "user:pass" --url "pop3://pop.example.com/"

# POP3: retrieve message #1
curl -u "user:pass" --url "pop3://pop.example.com/1"

# use IMAPS (implicit TLS, port 993)
curl -u "user:pass" --url "imaps://imap.example.com/INBOX"

FTPS と SFTP

FTP には 3 つの暗号化バリアントがあります:FTPS 明示的(--ftp-ssl、ポート 21 でアップグレード)、FTPS 暗黙的(ftps://、ポート 990 で最初から TLS)、SFTP(sftp://、ポート 22 の SSH 上の全く別のプロトコル)。SFTP は --key 経由の鍵認証に対応します(暗号化された鍵には --pass)。SFTP はシンプルさとファイアウォールの親和性から、今日では一般に FTPS より推奨されます。

curl
# FTPS: explicit TLS (upgrade to TLS on plain FTP port)
curl --ftp-ssl --ssl-reqd ftp://ftp.example.com/ -u user:pass

# FTPS: implicit TLS (TLS from the start, port 990)
curl ftps://ftp.example.com:990/ -u user:pass

# SFTP (SSH File Transfer Protocol, port 22)
curl -u user sftp://sftp.example.com/file.txt

# SFTP with key authentication
curl -u user --key ~/.ssh/id_rsa \
     sftp://sftp.example.com/file.txt

# SFTP with a password-protected key
curl -u user --key ~/.ssh/id_rsa --pass passphrase \
     sftp://sftp.example.com/file.txt

# SFTP upload
curl -u user -T local.txt sftp://sftp.example.com/remote.txt

# SFTP list directory
curl -u user sftp://sftp.example.com/
16

並列とバッチ

並列ダウンロード

curl 自体は逐次です — 同時にダウンロードするには、& と wait で複数の curl を並列に動かすか、xargs -P N で N 個を一度に実行しましょう。多くの小さなファイルで劇的に高速化します。配慮しましょう:並列接続が多すぎるとサーバーを圧迫したりレート制限を受けます。4〜8 の同時実行が妥当なデフォルトです。

curl
# background multiple curls (shell parallelism)
curl -O https://example.com/a.zip &
curl -O https://example.com/b.zip &
curl -O https://example.com/c.zip &
wait

# parallel with xargs (4 concurrent)
echo -e "https://example.com/a.zip\nhttps://example.com/b.zip" | \
  xargs -n1 -P4 curl -O

# parallel with a URL list file
xargs -n1 -P4 curl -O < urls.txt

# zsh-specific parallel with {..}
for url in https://example.com/{a,b,c}.zip; do
  curl -O "$url" &
done; wait

# bash-specific using arrays and &
urls=("https://example.com/a.zip" "https://example.com/b.zip")
for url in "${urls[@]}"; do curl -O "$url" & done; wait

xargs による並列

xargs -P N は N プロセスを同時に実行し、stdin の各行を引数として渡します。-a はファイルから読み込み、-I {} で URL をコマンドの任意の場所に置けます。追加ツールなしで curl ダウンロードを並列化する最も簡単な方法です。ホストを考慮したスロットリングや複雑なリトライロジックには、aria2c のような専用のダウンロードマネージャーを使いましょう。

curl
# download each URL from a file, 4 concurrent
xargs -n1 -P4 -a urls.txt curl -O

# download with custom names, parallel
cat urls.txt | xargs -n2 -P4 sh -c 'curl -o "$0" "$1"'

# download and process each response
cat urls.txt | xargs -n1 -P4 -I {} sh -c \
  'curl -s {} | jq .field'

# retry failures in parallel
xargs -n1 -P4 -a urls.txt curl --retry 3 -O

# limit total concurrent connections to a host
# (xargs doesn't know about hosts; use a queue or a download manager)
xargs -n1 -P4 -a urls.txt curl -O --limit-rate 1M

# show progress for parallel downloads
xargs -n1 -P4 -a urls.txt curl -O --progress-bar 2>&1

URL グロビング

グロビングは URL を複数のリクエストへ展開します:[1-10] の範囲(省略可能な :step と先頭ゼロによるゼロ埋め)と {a,b,c} のリストです。-o 'file#1.zip' はカスタム出力名のカウンタとして #1 を使います。-g(--globoff)は展開を無効化します — リテラルの [ ] や { }(JSON、IPv6)を含む URL には不可欠です。

curl
# numeric range: 1, 2, 3
curl -O https://example.com/file[1-3].zip

# range with step: 0, 5, 10, 15, 20
curl -O https://example.com/file[0-20:5].zip

# leading zeros (zero-padded)
curl -O https://example.com/file[01-10].zip   # 01, 02, ..., 10

# list expansion: a, b, c
curl -O https://example.com/{a,b,c}.zip

# nested globs
curl -O https://example.com/{v1,v2}/file[1-2].txt

# save each with a custom name pattern
curl -o "file#1.zip" https://example.com/file[1-3].zip

# disable globbing (literal brackets)
curl -g "https://example.com/file[1].zip"

逐次レンジ

逐次ダウンロード(並列化がサーバーを圧迫する、またはレート制限に違反する場合)には、bash で URL をループしましょう。礼儀のため sleep を加えます。-sf(silent + fail)で curl が HTTP エラー時に非ゼロで終了し、ループが早期に抜けられます。これがスクレイピングやクローリングの安全なパターンです:敬意を持ち、遅延を加え、エラーを処理しましょう。

curl
# fetch URLs one at a time (no parallelism)
for i in 1 2 3 4 5; do
  curl -O "https://example.com/page$i.html"
done

# range with brace expansion (bash/zsh)
for i in {1..10}; do
  curl -s -O "https://example.com/page$i.html"
done

# with a delay between requests (rate limiting)
for i in {1..10}; do
  curl -s -O "https://example.com/page$i.html"
  sleep 1
done

# retry each URL individually
for url in $(cat urls.txt); do
  curl -s --retry 3 -O "$url"
done

# conditional: stop on first error
for url in $(cat urls.txt); do
  curl -sf -O "$url" || { echo "failed: $url"; break; }
done

GNU Parallel と curl

GNU parallel は xargs より強力です:出力順を保ち、進捗を表示し(--bar)、引数をより柔軟に扱います。-j N が同時実行数を設定し、:::: はファイルから、::: はコマンドラインから読み込みます。Parallel は、並行リクエストからきれいで順序のある出力が必要な、バッチ API テスト、スクレイピング、ベンチマークに最適です。

curl
# GNU parallel: smarter than xargs (preserves order, progress)
parallel -j4 curl -O {} ::: https://example.com/a.zip \
                            https://example.com/b.zip

# parallel from a file
parallel -j4 curl -O :::: urls.txt

# parallel with progress bar
parallel --bar -j4 curl -O :::: urls.txt

# parallel with output capture
parallel -j4 'curl -s -o {}.out {}' :::: urls.txt

# parallel with retry and timing
parallel -j4 'curl -s -w "{} %{time_total}s\n" -o /dev/null {}' :::: urls.txt

# parallel POST requests
parallel -j4 'curl -s -X POST -d "id={}" https://api.example.com/{}' \
  ::: 1 2 3 4 5

# combine with --dry-run to preview
parallel --dry-run -j4 curl -O :::: urls.txt
17

設定ファイル

.curlrc の基本

~/.curlrc はすべての curl 実行に適用されるデフォルトオプションを保持します。先頭の -- を付けずに長いオプション名を使いましょう。1 行に 1 オプションで、値は引用符で囲めます。これでよく使う設定(タイムアウト、リトライ、User-Agent)がスクリプトと対話利用の間で一貫します。リクエストごとに上書きするには、コマンドラインで明示的にオプションを渡します。

curl
# ~/.curlrc is read automatically by curl
# one option per line, long option names without the --

# ~/.curlrc example:
# show progress by default
silent
# always follow redirects
location
# default User-Agent
user-agent = "MyApp/1.0"
# default headers
header = "Accept: application/json"
# retry transient errors
retry = 3
# connect timeout
connect-timeout = 10
# max time
max-time = 30

# lines starting with # are comments
# blank lines are ignored

# test: curl https://example.com now uses all the above

設定ファイルの場所

curl はデフォルトで ~/.curlrc(または $CURL_HOME/.curlrc)を読みます。-K(--config)が特定のファイルを指し、-K - は stdin から読み込みます。-q(--disable)は設定ファイルを完全にスキップします — デフォルトのオプションが特定のリクエストを壊すときに有用です。CURL_HOME はポータブルなセットアップのために検索ディレクトリを移動します。

curl
# default locations (searched in order):
# 1. ~/.curlrc (or $CURL_HOME/.curlrc)
# 2. /etc/curl/curlrc (system-wide, if compiled in)

# set a custom config directory
export CURL_HOME=/etc/curl
# curl then reads $CURL_HOME/.curlrc

# specify a config file explicitly
curl -K /path/to/myconfig https://example.com
curl --config /path/to/myconfig https://example.com

# read config from stdin
echo "silent" | curl -K - https://example.com

# disable config file reading
curl -q https://example.com
curl --disable https://example.com

# check which config curl reads
curl -v https://example.com 2>&1 | grep -i config

-K による設定

-K はファイルからオプションを読み込み、環境ごとの設定(dev と prod のトークン、タイムアウト、ヘッダー)に最適です。設定ファイル(chmod 600)にシークレットを保存すれば、シェルの履歴や ps から離れます。複数の -K ファイルは順に処理されるため、後のファイルが前のファイルを上書きします — ベース設定 + 環境固有の上書きに有用です。

curl
# use a config file for a specific request
curl -K prod.conf https://api.example.com/data

# prod.conf:
# header = "Authorization: Bearer prod-token"
# header = "X-Environment: production"
# connect-timeout = 5
# max-time = 20

# dev.conf (different settings)
# header = "Authorization: Bearer dev-token"
# header = "X-Environment: development"
# max-time = 60

# switch environments by config file
curl -K dev.conf https://api.example.com/data
curl -K prod.conf https://api.example.com/data

# config file with URL
# echo "url = https://api.example.com/data" > req.conf
curl -K req.conf

# multiple config files (later ones override earlier)
curl -K defaults.conf -K override.conf https://example.com

よくあるデフォルト

しっかりした ~/.curlrc はすべての curl 実行をより安全で一貫したものにします:タイムアウトがハングを防ぎ、リトライが一時的な失敗を処理し、--compressed が gzip を透過的に扱い、stripped な User-Agent がフィンガープリンティングを減らします。write-out の行はすべてのリクエストのタイミングとステータスを記録します — 手軽なパフォーマンスチェックに非常に有用です。

curl
# ~/.curlrc with sensible production defaults

# always follow redirects
location
# limit redirects
max-redirs = 5

# timeouts (fail fast, cap total)
connect-timeout = 10
max-time = 60

# retry transient failures
retry = 3
retry-delay = 2
retry-all-errors

# show errors even when silent
show-error

# auto-decompress responses
compressed

# negotiate HTTP/2
http2

# verify SSL by default (explicit for clarity)
cacert = /etc/ssl/certs/ca-certificates.crt

# don't leak the curl version
user-agent = ""

# verbose timing on failure
write-out = "time: %{time_total}s code: %{http_code}\n"

複数の設定

設定をレイヤー化したファイル(base、auth、api、environment)に分けると、モジュール化とセキュリティが保てます。複数の -K フラグで順に処理しましょう — 後のファイルが前のファイルを上書きします。シークレットはバージョン管理の外にある 600 権限のファイルに置きます。スタックをロードするラッパースクリプトがあれば、すべてのデフォルトが適用された 'mycurl' を呼び出せます。

curl
# base.conf — shared defaults
# silent
# show-error
# compressed
# connect-timeout = 10
# max-time = 30

# auth.conf — credentials (chmod 600)
# user = alice:secret
# header = "Authorization: Bearer TOKEN"

# api.conf — API-specific options
# header = "Accept: application/json"
# header = "X-Client: my-app/2.0"
# retry = 5

# combine configs in order (later overrides earlier)
curl -K base.conf -K auth.conf -K api.conf \
     https://api.example.com/data

# config file referencing another (nesting not supported)
# but you can source them in a wrapper script:
#   #!/bin/bash
#   curl -K base.conf -K auth.conf -K api.conf "$@"

# environment-specific overlay
curl -K base.conf -K "${ENV}.conf" https://api.example.com
18

高度なテクニック

接続の再利用

1 回の curl 実行内では、同じホストへの複数 URL で TCP 接続が再利用されます(HTTP keep-alive)— TLS ハンドシェイクのオーバーヘッドを節約します。--no-keepalive で無効化します。--max-connects はマルチ URL 取得の同時接続を上限とします。別々の curl 呼び出し間では接続は再利用されません — それには、httpie のような永続クライアントか Python/Node のスクリプトを使いましょう。

curl
# curl reuses connections within a single invocation
# multiple URLs in one command share the TCP connection
curl -o a.txt https://example.com/a \
     -o b.txt https://example.com/b

# keep-alive is on by default
# disable it for a single request
curl --no-keepalive https://example.com

# limit max connections (for multi-URL)
curl --max-connects 4 \
     -O https://example.com/a -O https://example.com/b

# persistent session across shell calls (not natively supported)
# but you can use a config file to reduce overhead
curl -K session.conf https://example.com/a
curl -K session.conf https://example.com/b

# check if connection was reused
curl -v https://example.com 2>&1 | grep -i "Connection #0"

HTTP/2 と HTTP/3

HTTP/2 は 1 接続上でリクエストを多重化し、HTTP/3 は UDP 上の QUIC を使い、先頭ブロッキングを解消します。--http2 は TLS 上で ALPN 経由で交渉し、--http2-prior-knowledge は交渉をスキップします(平文の h2c 用)。--http3 には特別な curl ビルドが必要です。実際に使われたものを確認するには %{http_version} を確認しましょう。多くのモダンな CDN はデフォルトで h2 に対応しています。

curl
# negotiate HTTP/2 (needs TLS + ALPN)
curl --http2 https://example.com

# force HTTP/2 (fail if not available)
curl --http2-only https://example.com

# negotiate HTTP/3 (QUIC, needs curl built with quiche/openssl-quic)
curl --http3 https://example.com

# force HTTP/3 only
curl --http3-only https://example.com

# check what version was negotiated
curl -s -o /dev/null -w "%{http_version}" https://example.com
echo   # 2 or 3

# list supported HTTP versions
curl --version | grep -i -E "http2|http3"

# HTTP/2 with prior knowledge (no upgrade negotiation)
curl --http2-prior-knowledge http://example.com

条件付きリクエスト

条件付きリクエストは帯域を節約します:リソースが変わっていなければ、サーバーは 304 Not Modified(ボディなし)を返します。-z(--time-cond)は日付かローカルファイルの mtime から If-Modified-Since を設定します。ETag ベースのキャッシュには If-None-Match を手動で設定しましょう。If-Unmodified-Since は楽観的並行性を可能にします — 他の人がリソースを変更していたら PUT が失敗します。

curl
# fetch only if modified since a date
curl -z "Wed, 21 Oct 2025 07:28:00 GMT" \
     -O https://example.com/data.json
curl --timecond "Wed, 21 Oct 2025 07:28:00 GMT" \
     -O https://example.com/data.json

# fetch only if changed (use a local file's mtime)
curl -z local_copy.json -O https://example.com/data.json

# ETag-based conditional (If-None-Match)
curl -H 'If-None-Match: "abc123"' \
     -o data.json https://example.com/data.json
# server returns 304 Not Modified if ETag matches

# If-Modified-Since header manually
curl -H "If-Modified-Since: Wed, 21 Oct 2025 07:28:00 GMT" \
     https://example.com/data.json

# If-Unmodified-Since (for concurrency control)
curl -X PUT -H "If-Unmodified-Since: Wed, 21 Oct 2025 07:28:00 GMT" \
     -d '{"x":1}' https://api.example.com/data

Interface と DNS

--interface はネットワークカードか IP に束縛します — マルチホームのマシンで有用です。--resolve はホストを IP に固定し DNS をバイパスするため、ロードバランサーの後ろのバックエンドのテストに最適です。--doh-url は DNS-over-HTTPS を使います(プライバシー)。-4/-6 が IP ファミリーを強制します。Happy Eyeballs(デフォルト)は IPv4 と IPv6 の両方を試し、IPv6 のブラックホール遅延を避けます。

curl
# bind to a specific network interface
curl --interface eth0 https://example.com
curl --interface 192.168.1.5 https://example.com

# pin a hostname to an IP (skip DNS)
curl --resolve example.com:443:1.2.3.4 https://example.com

# pin multiple hosts
curl --resolve example.com:443:1.2.3.4 \
     --resolve api.example.com:443:1.2.3.5 \
     https://example.com/

# use a custom DNS server (DoH)
curl --doh-url https://dns.google/dns-query https://example.com
curl --doh-url https://cloudflare-dns.com/dns-query https://example.com

# use a specific DNS resolver (plain DNS, curl 7.84+)
curl --dns-servers 8.8.8.8,1.1.1.1 https://example.com

# happy eyeballs: try IPv4 and IPv6 in parallel
curl --happy-eyeballs-timeout-ms 200 https://example.com

# force IPv4 or IPv6
curl -4 https://example.com
curl -6 https://example.com

Range リクエストと部分取得

Range リクエスト(-r)はファイルの一部を取得し、206 Partial Content が返ります。ユースケース:大きなファイルのプレビュー、並列の複数接続ダウンロード(範囲に分割し、同時に取得し、結合する)、中断された転送の再開(-C -)。サーバーが Accept-Ranges: bytes を宣伝している必要があります。これが aria2 のようなダウンロードアクセラレータの基礎です。

curl
# request a byte range (first 1024 bytes)
curl -r 0-1023 -o part.bin https://example.com/file.zip

# request from byte 1024 to end
curl -r 1024- -o rest.bin https://example.com/file.zip

# request last 500 bytes
curl -r -500 -o tail.bin https://example.com/file.zip

# check if server supports ranges
curl -I https://example.com/file.zip | grep -i accept-ranges

# download in parallel chunks
curl -r 0-49999999    -o part1.bin https://example.com/big.iso &
curl -r 50000000-     -o part2.bin https://example.com/big.iso &
wait
cat part1.bin part2.bin > big.iso

# resume a partial download
curl -C - -o file.zip https://example.com/file.zip

# HTTP 206 = Partial Content (range succeeded)
curl -r 0-100 -v https://example.com/file.zip 2>&1 | grep HTTP

終了コード

curl の終了コードは失敗モードを区別します:6(DNS)、7(接続)、22(HTTP エラー、-f があるときのみ)、28(タイムアウト)、35(TLS)、60(証明書)。これを使って、適切に再試行する堅牢なスクリプトを作りましょう(例:28 では再試行、6 では早く失敗)。--fail-with-body は 4xx/5xx でもレスポンスボディを返すため、API エラーのデバッグが -f よりはるかに容易になります。

curl
# common curl exit codes:
# 0  - success
# 1  - unsupported protocol
# 3  - malformed URL
# 6  - couldn't resolve host (DNS failure)
# 7  - failed to connect
# 22 - HTTP error (use with -f)
# 26 - couldn't read a file (e.g., -d @missing.txt)
# 28 - operation timeout
# 35 - SSL connect error
# 47 - too many redirects
# 52 - server didn't reply anything
# 55 - failed sending network data
# 56 - failed receiving network data
# 60 - certificate verification failed

# check exit code
curl -sf https://example.com || echo "failed: $?"

# branch on specific codes
curl --max-time 5 https://example.com
case $? in
  0)  echo "ok" ;;
  6)  echo "DNS failure" ;;
  7)  echo "connection refused" ;;
  28) echo "timeout" ;;
  *)  echo "error: $?" ;;
esac

# treat HTTP errors as failures
curl -f https://api.example.com || echo "HTTP error"

# still print body on HTTP error (7.76+)
curl --fail-with-body https://api.example.com

Was this helpful?