よく使うcurl コマンドのオプション Tips

エキサイトの山口です。 今回は業務中によく使っているcurlコマンドのオプション例を紹介します。

-X

POST GET PUT などのhttpメソッドの指定ができます。無指定であればGETになります。

curl -X POST http://localhost:8080/

--data-urlencode

POST時に送るデータを指定できます。複数の場合はさらに-dを後ろに連続でつけます。

curl -X POST --data-urlencode 'clientId=xxxx' -d 'uuid=xxxxxx' http://localhost:8080/

-L

リダイレクトを有効にします。

curl -L http://localhost:8080/

-m, –max-time

最大転送時間を指定秒に制限します。

curl -m 5 http://localhost:8080/

-A

ユーザーエージェントを指定します。

curl -A 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36' http://localhost:8080/

-H

HTTPヘッダを追加もしくは変更します。

curl -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3' http://localhost:8080/

-s

進捗情報やエラーを表示しないようにできます。

curl -s http://localhost:8080/

--retry

指定した回数だけリトライします。400系エラーや成功の場合はリトライしません。

curl --retry 3 http://localhost:8080/

-o

ファイルに出力します。

curl -o 出力先PATH http://localhost:8080/

-I

レスポンスHeaderのみを取得し、出力することができます。

curl -I excite.co.jp

curl -I excite.co.jp

HTTP/1.1 301 Moved Permanently
Date: Mon, 13 Feb 2023 03:36:50 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://www.excite.co.jp

-i

レスポンスHeaderとbodyどちらも取得し、出力することができます。

curl -i excite.co.jp

curl -i excite.co.jp

HTTP/1.1 301 Moved Permanently
Date: Mon, 13 Feb 2023 03:38:20 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://www.excite.co.jp

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>

-v

詳細な情報を表示することができます。

curl -v excite.co.jp

curl -v excite.co.jp

*   Trying xxxxxxx...
* Connected to excite.co.jp (xxxxxxxxxx) port 80 (#0)
> GET / HTTP/1.1
> Host: excite.co.jp
> User-Agent: curl/7.79.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 13 Feb 2023 03:48:59 GMT
< Content-Type: text/html
< Content-Length: 194
< Connection: keep-alive
< Location: https://www.excite.co.jp
<
<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
* Connection #0 to host excite.co.jp left intact

-w

送受信が終わった後に出力するテキストを指定します。%{変数名}で変数に対応した内容を指定できます。使用できる変数は決まっています。

curl excite.co.jp -w '%{http_code}\n'

curl excite.co.jp -w '%{http_code}\n'

<html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
301

-oと連用すると、ステータスコードだけを抜き取れます。

curl excite.co.jp -o /dev/null -w '%{http_code}\n' -s

curl excite.co.jp -o /dev/null -w '%{http_code}\n' -s

301

おわりに

業務でよく使うオプションを並べてみました。 基礎的なものですが、すぐに忘れがちなのでTIpsとして紹介させていただきました。 ぜひ使ってみてください。