How to print first line of the response and status code in curl


curl -o /dev/null -s -w "HTTPCode=%{http_code}_TotalTime%{time_total}s\n"

just gives me the status code

I also want the body of the response, How can i do that in the command?


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

curl -sw "HTTPCode=%{http_code}_TotalTime%{time_total}s\n"

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

curl -sw "HTTPCode=%{http_code}_TotalTime%{time_total}s\n" | 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" | sed -n '1p; $p;'
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">

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.


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

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

To explain the sed
sed -n says no output unless I ask for it.
1h; says on line 1, hold 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 means print the current pattern buffer, which on the last line will be the last line just read in.
  • x means exchange the hold and pattern buffers. This puts line 1, still in the hold buffer, into the standard pattern buffer space.
  • p again prints the new value of the pattern buffer, which is the held line 1.

Answered By – Paul Hodges

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published