BASH: How to Get HTTP Response Code using Curl Command?


To check the HTTP response code after running a curl command, you can use the -w option with curl, which allows you to specify a custom output format. Here’s the command:

curl -o /dev/null -s -w "%{http_code}\n" <URL>

You can save the HTTP response code into a BASH variable, like this:

resp=$(curl -o /dev/null -s -w "%{http_code}\n" <URL>)

Explanation:

  • -o /dev/null: Discards the output of the response body.
  • -s: Runs curl in silent mode (no progress or error messages).
  • -w “%{http_code}\n”: Outputs only the HTTP response code.

Replace <URL> with the actual URL you’re checking.

How to Get HTTP Response Code and Output?

To get the http output at the same time, you would need to use -o to redirect the output. For example:

resp=$(curl -s -w "%{http_code}" -o /tmp/curl_output.txt <URL>)

And the BASH variable $resp contains the HTTP response code, and the /tmp/curl_output.txt contains the request output.

BASH Programming/Shell

–EOF (The Ultimate Computing & Technology Blog) —

267 words
Last Post: Teaching Kids Programming - Compute the Range Sum with Update: A Deep Dive into Segment Tree, SQRT Decomposition, Brute Force & Prefix Sum
Next Post: Toss a Coin 256 Times: The Math Behind an Unbreakable Bitcoin Private Key

The Permanent URL is: BASH: How to Get HTTP Response Code using Curl Command? (AMP Version)

Leave a Reply