How to Get HTTP Status Code Using Curl Write Out

When automating web requests or debugging APIs, extracting the HTTP status code is a common requirement. This article provides a quick and direct guide on how to use the curl command’s --write-out (or -w) option to isolate and extract the HTTP status code from a server response, complete with practical command examples for different use cases.

The Basic Command

To extract only the HTTP status code using curl, you use the -w or --write-out option followed by the format variable %{http_code}.

Here is the standard command:

curl -s -o /dev/null -w "%{http_code}" https://example.com

How It Works

Adding a Newline for Readability

By default, the command above prints the status code without a trailing newline, which can make it blend into your terminal prompt. You can append \n to the format string to add a newline:

curl -s -o /dev/null -w "%{http_code}\n" https://example.com

Storing the Status Code in a Bash Variable

In shell scripting, you often need to store the status code in a variable to perform conditional logic. You can achieve this using command substitution:

status_code=$(curl -s -o /dev/null -w "%{http_code}" https://example.com)

if [ "$status_code" -eq 200 ]; then
    echo "Success: The website is up and running."
else
    echo "Failure: Received HTTP status code $status_code"
fi