Linux Labs

Bash: text processing and scripts / Stage 7 of 9

Exit status and a healthcheck

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 8 · on a machine · 6 min

Exit status

Every command reports a number as it finishes — it tells whether the command succeeded.

That number is the exit status, the same one a script sets with exit N. Zero means success; any number from 1 to 255 means a failure, and the number points to the cause. Each program has its own numbers: for curl, 6 means the server name was not found, 7 that connecting failed, 28 that the wait timed out. The status does not reach the screen — the shell keeps it.

The last command's status sits in the $? variable, and echo prints it. That way you will see how curl's request to the app that is down ended.

Exercise · look

Look at curl's exit status

In ~/health-lab, run two commands: a request to the app that prints curl's exit status, then print $? once more.

First, predict

The first command prints curl's exit status. What will the second print?

Now start the exercise, run the command and compare your prediction with the output.

Sign in and start The machine is available after signing in

$? holds the status of one command — the last one. Any next command, even echo, puts its own status there. So $? is read right after the command you need: one line further down, it already belongs to another command.

In healthcheck.sh, echo "checked at …" sits between curl and the condition. The if [ $? -eq 0 ] condition got the status of that echo — zero — and the script printed OK.

Ubuntu 24.04
Loading…