如何从 cURL 中的内容中拆分 HTTP 错误代码?

0xC*_*22L 6 bash curl

是的,这与让 curl 输出 HTTP 状态代码有关?但不幸的是不一样。

在我想运行的脚本中:

curl -qSfsw %{http_code} URL
Run Code Online (Sandbox Code Playgroud)

其中该-f选项确保退出代码非零以表示错误。成功时,我想从获取的文件中获取(文本)输出,否则我想使用错误代码。

问题:

  • 由于竞争条件,我不能使用多个 HTTP 请求
  • 我不能使用临时文件来存储内容

我怎样才能从实际输出中分离 HTTP 返回码?


伪代码:

fetch URL
if http-error then
  print http-error-code
else
  print http-body # <- but without the HTTP status code
endif
Run Code Online (Sandbox Code Playgroud)

Dan*_*eck 17

无需使用临时文件。以下 bash 脚本片段发送单个请求并打印curlHTTP 状态代码或 HTTP 状态代码和响应(视情况而定)的退出代码。

# get output, append HTTP status code in separate line, discard error message
OUT=$( curl -qSfsw '\n%{http_code}' http://superuser.com ) 2>/dev/null

# get exit code
RET=$?

if [[ $RET -ne 0 ]] ; then
    # if error exit code, print exit code
    echo "Error $RET"

    # print HTTP error
    echo "HTTP Error: $(echo "$OUT" | tail -n1 )"
else
    # otherwise print last line of output, i.e. HTTP status code
    echo "Success, HTTP status is:"
    echo "$OUT" | tail -n1

    # and print all but the last line, i.e. the regular response
    echo "Response is:"
    echo "$OUT" | head -n-1
fi
Run Code Online (Sandbox Code Playgroud)

head -n-1 (打印除最后一行之外的所有内容)需要 GNU,在 BSD/OS X 上不起作用。