To capture the HTTP return code from a curl command into a variable, use the -w % {http_code} write-out option combined with shell command substitution. Assign the output directly to your variable using syntax like HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" URL). This approach ensures you can programmatically check the status without parsing verbose output.
Understanding CURL Exit Codes vs HTTP Status Codes
It is crucial to distinguish between the exit status of the curl process itself and the HTTP status code returned by the server. The exit status, accessible via the $? variable in Bash or similar shells, indicates whether the command executed successfully. For example, an exit code of 0 means curl ran without error, while codes like 6 (could not resolve host) or 7 (failed to connect) indicate network-level failures.
The HTTP status code, such as 200 for OK or 404 for Not Found, is part of the response payload from the remote server. Even if the server returns a 4xx or 5xx error, curl may still exit with code 0 unless specific flags are used. Therefore, relying solely on the exit code is insufficient for application logic that depends on the server's response state. You must explicitly extract the HTTP status code using the write-out format string.
Basic Syntax for Capturing the Return Code
The most robust method involves using the -w (write-out) flag. This flag allows you to specify a format string that curl prints after the transfer is complete. By combining this with the -s (silent) flag and redirecting the body output, you isolate only the status code in your variable.
#!/bin/bash
# Define the URL
URL="https://example.com/api/health"
# Execute curl and capture the HTTP status code
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$URL")
# Check the result
if [ "$HTTP_STATUS" -eq 200 ]; then
echo "Success: Server responded with $HTTP_STATUS"
else
echo "Failure: Server responded with $HTTP_STATUS"
fi
In this script, -o /dev/null discards the actual content of the response, which is unnecessary if you only care about the status. The -s flag suppresses the progress meter and error messages, ensuring that only the status code is captured in the variable. The %{http_code} placeholder is replaced by the numeric HTTP status before being stored in HTTP_STATUS.
Handling Errors and Timeouts
When dealing with unreliable networks or strict timeouts, you should also capture the exit code to differentiate between a bad server response and a connection failure. Combining both checks provides a comprehensive view of the request's health.
# Set timeout to 10 seconds
TIMEOUT=10
# Run curl with silent mode and capture both status and exit code
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" --max-time "$TIMEOUT" "$URL")
EXIT_CODE=$?
if [ "$EXIT_CODE" -ne 0 ]; then
echo "Curl failed with exit code $EXIT_CODE"
elif [ "$HTTP_STATUS" -eq 200 ]; then
echo "Request successful"
else
echo "Server error: $HTTP_STATUS"
fi
This pattern is essential for automation scripts where you need to retry requests or alert administrators based on specific failure modes. Note that if the connection fails entirely, %{http_code} will typically return 000, which helps distinguish it from a valid but erroneous server response.
Advanced Formatting Options
Beyond the basic status code, curl allows you to capture additional metadata such as the total time taken, the size of the download, or the final URL after redirects. This is useful for performance monitoring or debugging complex redirection chains.
# Capture multiple values separated by newlines
OUTPUT=$(curl -s -o /dev/null -w "time_total:%{time_total}\nhttp_code:%{http_code}\nsize_download:%{size_download}" "$URL")
# Parse the output if necessary
echo "$OUTPUT"
You can parse this multi-line output using tools like awk or grep if you need individual metrics. However, for simple status checking, sticking to just %{http_code} keeps the script clean and efficient. If you are working with APIs that require authentication, ensure your headers are passed correctly, as malformed headers can lead to unexpected status codes. For more details on handling cookies during these requests, see Google Chrome DevTools 'Copy cURL' No Longer Includes Cookies?.
Common Pitfalls and Troubleshooting
One common mistake is forgetting to quote the variable when comparing it. Always use quotes around "$HTTP_STATUS" to prevent syntax errors if the variable is empty. Another issue arises when using curl in pipelines; ensure you are capturing the output of the last command in the pipe if you are chaining commands.
Additionally, some environments might have aliases or wrappers for curl that change default behaviors. Verify you are calling the standard binary by using its full path if necessary. If you are saving response bodies alongside status codes, consider how to manage file outputs efficiently. A related guide on managing response content types can be found at How to Save curl.exe Output Response Content_Type to a Separate File.
Frequently Asked Questions
What does http_code 000 mean?
An HTTP status code of 000 indicates that curl was unable to retrieve any status code from the server. This usually happens when the connection fails, times out, or is refused before a valid HTTP response is received. It signals a network-level issue rather than a server-side application error.
Can I capture the status code without suppressing the output?
Yes, but you must carefully separate the status code from the response body. Using -w appends the status code to the end of the output stream. If you do not redirect the body to /dev/null, your variable will contain both the HTML/json content and the status code, making parsing difficult. It is best practice to discard the body if you only need the status.
How do I handle redirects automatically?
Use the -L flag to tell curl to follow redirects. When following redirects, %{http_code} returns the status code of the final resource reached, not the intermediate redirect responses. This is generally the desired behavior for checking the ultimate success of a request.
Is there a difference between bash and zsh for this command?
No, the syntax for command substitution $(...) and environment variables works identically in Bash, Zsh, and other POSIX-compliant shells. The curl flags and write-out strings are also consistent across all major Unix-like operating systems.
Why is my script failing even with a 200 status code?
If your logic depends on the exit code ($?) instead of the HTTP status, note that curl exits with 0 for successful transfers regardless of the HTTP status (unless you use -f). Ensure your conditional statements check the captured HTTP_STATUS variable, not just the shell exit code, to accurately reflect server responses.