Turn service checks into reusable Bash scripts

Start with curl and learn variables, arguments, conditions, loops, and exit statuses to build reusable Node.js health checks.

🎯 Introduction

After deploying Node.js, we often use curl to check an endpoint. Retyping commands for every release is tedious and makes checks easy to miss.

A Bash script stores those commands in a file so you can repeat the same checks by running it. Using /health, this article introduces variables, arguments, conditions, loops, and exit statuses. The final scripts report success or failure and retry while a service is starting.

Prerequisite: A Node.js service is running on 127.0.0.1:3000, providing GET /health and returning HTTP 200 when healthy. Substitute your own port or route if needed. All output below is illustrative; actual results depend on whether your service is running.


🧱 From command to script

In a terminal, the shell executes commands as you enter them. A shell script stores several commands in a file for later execution together. We use Bash, with filenames typically ending in .sh.

First check the endpoint with one command:

curl -i http://127.0.0.1:3000/health

-i includes HTTP response headers. A healthy service produces a status line such as HTTP/1.1 200 OK. The script only needs the status code, not the full response.

1. Store the URL in a variable

check_url="http://127.0.0.1:3000/health"
echo "$check_url"

Example output:

http://127.0.0.1:3000/health

check_url is the variable name; the value is on the right of =. Do not put spaces around = in an assignment. Use $check_url to read the value. Changing the URL then requires editing only one place.

2. Obtain the HTTP status code

curl -sS --max-time 3 -o /dev/null -w '%{http_code}' -- "$check_url"

A healthy endpoint may output:

200

The options mean: -sS hides progress but still displays request errors; --max-time 3 limits the request to 3 seconds; -o /dev/null discards the body; -w '%{http_code}' prints only the HTTP status code; -- ends option parsing.

To inspect the status later, store the command's output:

http_status=$(curl -sS --max-time 3 -o /dev/null -w '%{http_code}' -- "$check_url")
echo "$http_status"

$(...) runs the enclosed command and assigns its output to http_status. If the endpoint returns 200, that is the stored value.

3. Decide whether the check passed

Create a script directory and edit the file with Vim:

mkdir -p "$HOME/linux-lab/bin"
vim "$HOME/linux-lab/bin/health-check.sh"

Save the complete code below, or download the example: health-check.sh.

health-check.sh
#!/bin/bash

check_url=${1:-http://127.0.0.1:3000/health}

if http_status=$(curl -sS --max-time 3 -o /dev/null -w '%{http_code}' -- "$check_url") &&
    [[ "$http_status" == 200 ]]; then
    printf 'OK %s\n' "$check_url"
    exit 0
fi

printf 'FAILED %s\n' "$check_url" >&2
exit 1

The script does three things in order:

  1. Select the URL: ${1:-default_url} uses the first script argument, $1, when supplied and nonempty; otherwise it uses the default /health URL.
  2. Check the endpoint: if requires both a successful curl command and [[ "$http_status" == 200 ]]. && evaluates the second condition only if the first succeeds. then begins the success branch, and fi ends the conditional.
  3. Return the result: On success, printf prints OK and exit 0 ends the script. Otherwise it prints FAILED and exits with 1. \n represents a newline; >&2 sends the failure message to standard error so tools can distinguish it from normal output.

The first line, #!/bin/bash, selects Bash when the file is executed directly. Running bash filename already specifies the interpreter explicitly.

Success has a precise definition here: the request completes successfully and the HTTP status is exactly 200. A 404, 500, or timeout fails the check. Other 2xx codes also fail this script's check, even though they indicate successful HTTP requests.


🛠 Run the script and read its exit status

Run the script, then immediately inspect its status:

bash "$HOME/linux-lab/bin/health-check.sh"
printf 'Exit status %s\n' "$?"

If /health returns 200, example output is:

OK http://127.0.0.1:3000/health
Exit status 0

If the endpoint is unreachable or does not return 200, you may see:

FAILED http://127.0.0.1:3000/health
Exit status 1

For connection failures, curl may print an additional error. An exit status is the number returned when a command ends: 0 generally means success, and nonzero means failure. $? contains the status of the immediately preceding command, so inspect it directly after running the script.

You can also grant execute permission and run the file directly:

chmod u+x "$HOME/linux-lab/bin/health-check.sh"
"$HOME/linux-lab/bin/health-check.sh" http://127.0.0.1:3000/api/notes

u+x adds execute permission for the owner. The final URL is the script's first argument and overrides the default /health URL.

This script checks only whether the endpoint returns 200. A 200 response does not necessarily mean dependencies such as a database are healthy. The application must provide an appropriate health endpoint to check them.


🧰 Check several endpoints and wait for startup with loops

1. Check endpoints in sequence with for

To check /health and /api/notes after deployment, use a for loop instead of typing two commands. It passes each route to the same check script:

for route in /health /api/notes; do
    bash "$HOME/linux-lab/bin/health-check.sh" "http://127.0.0.1:3000$route"
done

On the first iteration, route is /health; on the second, /api/notes. do begins the loop body, and done ends it. If both endpoints return 200, output looks like:

OK http://127.0.0.1:3000/health
OK http://127.0.0.1:3000/api/notes

This loop runs every check in sequence and does not stop automatically when one fails. Combining results into one exit status requires additional handling. For now, focus on the basic for syntax.

2. Wait for startup with while

A newly started Node.js service may not be listening yet. A single check could mistake incomplete startup for a persistent failure. A while loop can try up to three times and stop on success.

Save the following as another script so it can report failure accurately to other tools if all three attempts fail:

vim "$HOME/linux-lab/bin/wait-for-health.sh"
wait-for-health.sh
#!/bin/bash

attempt=1

while [[ "$attempt" -le 3 ]]; do
    if bash "$HOME/linux-lab/bin/health-check.sh"; then
        printf 'Service is ready\n'
        exit 0
    fi

    attempt=$((attempt + 1))
    if [[ "$attempt" -le 3 ]]; then
        sleep 1
    fi
done

printf 'Service is still not ready after three attempts\n' >&2
exit 1

Execution proceeds as follows:

  1. attempt=1 starts with the first check.
  2. [[ "$attempt" -le 3 ]] continues the loop while the attempt number is less than or equal to 3.
  3. A successful health check triggers exit 0, ending the entire waiting script. Otherwise, $((attempt + 1)) increments the count.
  4. If another attempt remains, sleep 1 waits one second. After three failures, the loop ends and the script exits with 1.

Run it and inspect the final result:

bash "$HOME/linux-lab/bin/wait-for-health.sh"
printf 'Exit status %s\n' "$?"

If the first check succeeds, it immediately prints Service is ready and exits with 0. If all three fail, it prints FAILED three times, followed by Service is still not ready after three attempts, and exits with 1.

A deployment workflow can now use the waiting script's own exit status to decide whether to continue, instead of mistakenly treating a final successful sleep as a successful check.


❓ Knowledge check

Q1: Why put the URL in double quotes?

Double quotes keep the expanded value as one argument, avoiding unexpected splitting or wildcard expansion. Keep them even when the current URL has no spaces.

Q2: How does printing FAILED differ from exit 1?

FAILED is a message for people; exit 1 is a failure status for the caller. Other scripts and automation tools can use that status to decide whether to continue.

Q3: Why check both curl's success and a 200 status?

Completing a request and receiving the expected application result are different. For example, curl usually completes successfully for a 404 response, but that does not mean the checked endpoint is healthy.


🧪 Exercise

Use health-check.sh to verify:

  1. With local /health returning 200, run the script and immediately print $?. Expect OK and 0.
  2. Change the URL to http://127.0.0.1:3000/missing, ensuring that route returns 404. Run again and expect FAILED and 1.
  3. Run if bash "$HOME/linux-lab/bin/health-check.sh"; then printf 'ready\n'; fi and verify that ready appears only on success.
  4. Stop the local service and run wait-for-health.sh. Confirm that it checks at most three times and returns 1 if every attempt fails.

If your service has no /health, substitute an endpoint known to return 200. The point is to verify that printed results and exit statuses agree.


🎉 You have turned a manual endpoint check into a reusable Bash script whose exit status lets other programs interpret the result!