Curl to return http status code along with the response
I found this question because I wanted independent access to BOTH the response and the content in order to add some error handling for the user.
Curl allows you to customize output. You can print the HTTP status code to std out and write the contents to another file.
curl -s -o response.txt -w "%{http_code}" http://example.com
This allows you to check the return code and then decide if the response is worth printing, processing, logging, etc.
http_response=$(curl -s -o response.txt -w "%{http_code}" http://example.com)if [ $http_response != "200" ]; then # handle errorelse echo "Server returned:" cat response.txt fi
The %{http_code}
is a variable substituted by curl. You can do a lot more, or send code to stderr, etc. See curl manual and the --write-out
option.
-w, --write-out
Make curl display information on stdout after a completedtransfer. The format is a string that may contain plaintext mixed with any number of variables. The format can bespecified as a literal "string", or you can have curl readthe format from a file with "@filename" and to tell curlto read the format from stdin you write "@-".
The variables present in the output format will besubstituted by the value or text that curl thinks fit, asdescribed below. All variables are specified as%{variable_name} and to output a normal % you just writethem as %%. You can output a newline by using \n, acarriage return with \r and a tab space with \t.
The output will be written to standard output, but thiscan be switched to standard error by using %{stderr}.