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.comHow It Works
-s(Silent Mode): Hides the progress meter and error messages, ensuring they do not clutter your output.-o /dev/null(Redirect Output): Redirects the actual response body of the website to/dev/null(essentially discarding it), so you only see the status code. On Windows PowerShell, use-o NULinstead.-w "%{http_code}"(Write Out): Instructscurlto output specific information after a completed transfer.%{http_code}is the variable that holds the numerical HTTP response code (e.g., 200, 404, 500).
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.comStoring 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