在 shell 脚本中从 curl 检索 HTTP 状态代码和内容

Chr*_*oll 3 shell-script curl

我想要一个脚本来卷曲到一个文件并将状态代码放入一个变量中(或者,至少让我能够测试状态代码)

我可以看到我可以在两个电话中完成,例如

url=https://www.gitignore.io/api/nonexistentlanguage
x=$(curl -sI $url | grep HTTP | grep -oe '\d\d\d')
if [[ $x != 200  ]] ; then
  echo "$url SAID $x" ; return
fi
curl $url # etc ...
Run Code Online (Sandbox Code Playgroud)

但大概有一种方法可以避免多余的额外调用?

$? 没有帮助:状态码 404 仍然得到 0 的返回码

GMa*_*ter 14

#!/bin/bash

URL="https://www.gitignore.io/api/nonexistentlanguage"

response=$(curl -s -w "%{http_code}" $URL)

http_code=$(tail -n1 <<< "$response")  # get the last line
content=$(sed '$ d' <<< "$response")   # get all but the last line which contains the status code

echo "$http_code"
echo "$content"
Run Code Online (Sandbox Code Playgroud)

(还有其他方法,比如--write-out临时文件。但我的例子不需要触摸磁盘写入任何临时文件并记住删除它;一切都在RAM中完成)

  • 几乎!在我的系统 (OSX) 上,我需要在 http_code "'\n%{http_code}'%{http_code}" 之前换行 (5认同)