如何在curl中打印响应和状态代码的第一行

wnavrhmk  于 2022-11-13  发布在  其他
关注(0)|答案(2)|浏览(318)
curl -o /dev/null -s -w "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" http://test.com

只会给我状态码
我也想要回应的主体,我如何在命令中做到这一点?

olhwl3o2

olhwl3o21#

Don't send it to /dev/null? -o is throwing it away.

curl -sw "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" http://test.com

If you ONLY want the first line, as your title suggests, filter it.

curl -sw "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" http://test.com | sed -n '1p; $p;'

This tells sed to print the first and last lines, because you asked for the first one, and -w prints after completetion. My test:

$: curl -s -w "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" google.com | sed -n '1p; $p;'
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
HTTPCode=301_TotalTime0.270267s

If you specifically mean the first line of the body from the response, now you need to define "first line" a little, and you should really get an HTML-aware parser. I could probably do it in sed , but it's really kind of a bad idea in most cases.
If that's really what you need, let me know, supply some additional details, and we'll work on it.

edit

OP requested the lines be in the reverse order, so I offered this:

$: curl -s -w "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" google.com | sed -n '1h; ${p;x;p;}'
HTTPCode=301_TotalTime0.270267s
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">

To explain the sed -
sed -n says n o output unless I ask for it.
1h; says on line 1, h old the data in the pattern buffer (the line just read, since we haven't edited it) in the "hold" buffer.
${ says on the last line, open a set of commands to execute, which will be closed with the matching } close brace.
p;x;p; -

  • p means p rint the current pattern buffer, which on the last line will be the last line just read in.
  • x means e x change the hold and pattern buffers. This puts line 1, still in the h old buffer, into the standard pattern buffer space.
  • p again p rints the new value of the pattern buffer, which is the held line 1.
dly7yett

dly7yett2#

您可以使用以下curl + awk解决方案:

curl -sw "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" 'http://test.com' |
awk '{p=p $0 ORS} END{print; sub(/\n[^\n]+\n$/, "", p); print p}'

相关问题