10

I read https://superuser.com/questions/272265/getting-curl-to-output-http-status-code . It mentioned that

curl -i 

will print the HTTP response code. Is it possible to have curl print just the HTTP response code? Is there a generic way to get the HTTP status code for any type of request like GET/POST/etc?

I am using curl 7.54.0 on Mac OS High Sierra.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
user674669
  • 10,681
  • 15
  • 72
  • 105
  • Does this answer your question? [Curl to return http status code along with the response](https://stackoverflow.com/questions/38906626/curl-to-return-http-status-code-along-with-the-response) – Nitish Kumar Feb 04 '22 at 05:49

3 Answers3

19

This worked for me:

$  curl -s -w "%{http_code}\n" http://google.com/ -o /dev/null
user674669
  • 10,681
  • 15
  • 72
  • 105
  • 1
    If you prefer longhand param names: `-s` = `--silent`, `-w` = `--write-out`, `-o` = `--output` – jakub.g Jun 10 '22 at 15:00
2
curl -s -I http://example.org | grep HTTP/ | awk {'print $2'}

output: 200

Uladzimir
  • 3,067
  • 36
  • 30
  • Thank you. I read the curl man page. -I will send HEAD request. Is there a generic way to get the HTTP status code for GET/POST/etc? – user674669 Nov 28 '18 at 19:09
  • but it's rare case, normally it's invoked by using dedicated command line options, for example `--upload-file` for PUT – Uladzimir Nov 28 '18 at 19:16
0

Another solution:

curl -sI http://example.org | head -n 1 | cut -d ' ' -f 2

in this way you are:

  1. getting the first HTTP response line (head -n 1), which must contain the response HTTP version, the response code and the response message (in this order), each one separated by a whitespace (as defined in the HTTP standard);
  2. getting the 2° field of this line (cut -d ' ' -f 2), which is the status code
Ricky Sixx
  • 581
  • 1
  • 10
  • 25