BASH: 如何使用 cURL 命令获取 HTTP 响应代码?

in cn •  10 days ago 

检查运行 curl命令 后的HTTP响应代码,您可以使用 curl 的 -w` 选项,这样可以指定自定义输出格式。以下是命令:

curl -o /dev/null -s -w "%{http_code}\n" <URL> 

您可以将HTTP响应代码保存到BASH变量中,如下所示:

resp=$(curl -o /dev/null -s -w "%{http_code}\n" <URL>) 

解释:

  • -o /dev/null: 丢弃响应体的输出。
  • -s: 以静默模式运行curl(不显示进度或错误信息)。
  • -w "%{http_code}\n": 仅输出HTTP响应代码。

将 <url> 替换为您正在检查的实际URL。

如何获取HTTP响应代码和输出?


如果您想同时获取HTTP输出,您需要使用 -o 来重定向输出。例如:

resp=$(curl -s -w "%{http_code}" -o /tmp/curl_output.txt <URL>) 

然后,BASH 变量 $resp 包含HTTP响应代码,而文件 /tmp/curl_output.txt 则会保存请求的输出文本。

BASH小技巧

英文:How to Get HTTP Response Code using cURL Command?

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!