Basic usage

We can easily get the HTTP response/status code of a URL and store it in a variable using Bash:

PRODUCTION_RESPONSE=$(curl --write-out '%{response_code}' --head --silent --output /dev/null

Replace with the desired URL.

Authenticated request

To perform a curl request to a password-protected URL that uses the basic HTTP server authentication:

STAGING_RESPONSE=$(curl --user USERNAME:PASSWORD --write-out '%{response_code}' --head --silent --output /dev/null

Replace USERNAME and PASSWORD with the relevant details.

If you don’t want to include the password in the Bash script, you can specify only the USERNAME part (--user USERNAME).

In this case, curl will ask you to enter the password manually in the terminal.

Further usage

We can then perform various actions based on the response code.

For example:


PRODUCTION_RESPONSE=$(curl --write-out '%{response_code}' --head --silent --output /dev/null $PRODUCTION_URL)

echo -e "Production status code:"

if [ "$PRODUCTION_RESPONSE" == "200" ]

In the above code, we display the response code in different colors: green for 200 (OK) and red for all other response codes.

Note that you will need to set these color variables first.

To learn more, check out my other post on text formatting in Bash.