Curl to return http status code along with the response

the verbose mode will tell you everything

curl -v http://localhost

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 error
else
    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 completed transfer. The format is a string that may contain plain text mixed with any number of variables. The format can be specified as a literal "string", or you can have curl read the format from a file with "@filename" and to tell curl to read the format from stdin you write "@-".

The variables present in the output format will be substituted by the value or text that curl thinks fit, as described below. All variables are specified as %{variable_name} and to output a normal % you just write them as %%. You can output a newline by using \n, a carriage return with \r and a tab space with \t.

The output will be written to standard output, but this can be switched to standard error by using %{stderr}.

https://man7.org/linux/man-pages/man1/curl.1.html


I was able to get a solution by looking at the curl doc which specifies to use - for the output to get the output to stdout.

curl -o - -I http://localhost

To get the response with just the http return code, I could just do

curl -o /dev/null -s -w "%{http_code}\n" http://localhost

Tags:

Shell

Curl