curl -w 的参数说明
curl -w
(或 curl --write-out
)用于自定义输出格式,可以提取特定的响应信息,例如 HTTP 状态码、重定向后的 URL、下载速度等。
1. -w
选项的语法
curl -w "<格式字符串>" <URL>
<格式字符串>
:可以包含变量(以 %{}
包围),这些变量会被替换为实际的请求信息。
2. -w
选项的常见变量
变量 | 作用 |
%{url_effective} | 最终请求的 URL(包括重定向后) |
%{http_code} | HTTP 状态码(如 200 , 404 , 500 ) |
%{time_total} | 总请求时间(秒) |
%{time_connect} | 建立连接所需时间(秒) |
%{time_starttransfer} | 服务器开始传输数据的时间(秒) |
%{size_download} | 下载的数据大小(字节) |
%{size_upload} | 上传的数据大小(字节) |
%{speed_download} | 平均下载速度(字节/秒) |
%{speed_upload} | 平均上传速度(字节/秒) |
3. 示例用法
(1)获取最终跳转后的 URL
curl -sL -w "%{url_effective}" -o /dev/null https://github.com/goreleaser/goreleaser/releases/latest
输出(如 https://github.com/goreleaser/goreleaser/releases/tag/v1.23.0
):
https://github.com/goreleaser/goreleaser/releases/tag/v1.23.0
这里 -o /dev/null
用于丢弃请求的 HTML 内容,只保留 -w
输出的结果。
(2)获取 HTTP 状态码
curl -s -o /dev/null -w "%{http_code}" https://httpbin.org/status/404
输出:
404
(3)获取请求耗时
curl -s -o /dev/null -w "Total time: %{time_total}s\n" https://example.com
输出:
Total time: 0.235s
(4)获取下载大小 & 速度
curl -s -o /dev/null -w "Downloaded: %{size_download} bytes at %{speed_download} bytes/sec\n" https://example.com
输出:
Downloaded: 1250 bytes at 50000 bytes/sec
4. 结合多个变量
可以使用 \n
换行,或 \t
进行对齐:
curl -s -o /dev/null -w "URL: %{url_effective}\nStatus: %{http_code}\nTime: %{time_total}s\n" https://example.com
输出:
URL: https://example.com
Status: 200
Time: 0.123s
5. 结合 echo
& jq
生成 JSON 格式
curl -s -o /dev/null -w '{"url":"%{url_effective}","status":%{http_code},"time":%{time_total}}\n' https://example.com | jq .
输出:
{
"url": "https://example.com",
"status": 200,
"time": 0.123
}
6. 总结
curl -w
可以格式化输出,提取 HTTP 请求的关键信息。
-w
可与 -o /dev/null
结合,仅输出所需数据。
- 可以结合
jq
生成 JSON 结构化数据。