>_ IzzyLab

Hands-on task

This task is step 8 of the course “Your first bash script”

Exit code: a health-check script

easy~7 min

The service manager checks the app with a script and looks only at its exit code: 0 means all is well, anything else means something is wrong. Write /root/healthcheck.sh:

  • if the file /root/app/ready exists, it prints healthy and exits with code 0;
  • if there's no such file, it prints unhealthy and exits with code 1.

Right now the file doesn't exist. Check both cases: run the script and look at the exit code, then create the file and run it again.

What you'll practise:
  • bash scripts
  • exit code
  • exit
  • $?

Topic breakdown

Every command returns an exit code when it finishes — a number from 0 to 255. 0 means "success", any other number means "error", and different numbers can mean different errors. The code isn't printed on the screen; it's in the variable $? — but only until the next command:

ls /etc >/dev/null; echo $?    # 0
ls /nope;          echo $?    # 2 — no such directory

if, && and || look at the exit code, and so do service managers, cron and CI: that's how they decide whether everything went well.

A script sets its own code with the exit command:

#!/bin/bash
if [ "$#" -eq 0 ]; then
    echo "an argument is required"
    exit 2
fi
echo "working with $1"

exit ends the script immediately — the lines after it don't run. If there's no exit, the script's exit code is the code of its last command.

What's checked

  1. /root/healthcheck.sh created
  2. With the file: healthy and code 0
  3. Without the file: unhealthy and code 1

What it looks like