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 3 of 8 · theory · 4 min

A condition on a command's status

For the condition to look at curl, there is no need to read $?: if checks a command by itself.

if runs the command that follows it and picks a branch by its status: zero — then, any other number — else. The square brackets from the lesson on script arguments are a command too: [ $? -eq 0 ] compares numbers and ends with status 0 or 1. So curl goes straight into the condition:

bash
URL=http://127.0.0.1:8080/health
if curl -s -o /dev/null "$URL"; then
    echo "OK"
else
    echo "FAIL"
    exit 1
fi

A shorter way to write the same is && and ||. a && b runs b only if a ended with status 0, a || b only if it ended with another status. If you need the status later, save it at once: rc=$? on the first line after the command.

A script has its own status as well — the status of its last command or the number given to exit. A timer, cron and monitoring read that status; they do not parse the printed text. That is why the failure branch has exit 1: without it, a script that printed FAIL ends with the status of echo.

Check yourself 1 question

The check.sh script is two lines. The app is stopped. What exit status will ./check.sh end with?

URL=http://127.0.0.1:8080/health
curl -s -o /dev/null "$URL" && echo OK || echo FAIL
  • The script would return 1 with exit 1. The last command to run was echo FAIL, and the script's status is its zero: check with ./check.sh; echo $?.

  • 7 is curl's status, but echo FAIL ran after it. The script's status is that of its last command, zero.

curl failed, || ran echo FAIL, and the script ended with its status, zero. A timer sees success even though the screen says FAIL; an exit 1 in the failure branch gives an honest status.

Key points

  • if command picks a branch by that command's status; [ … ] is just such a command.
  • a && b runs b after a succeeds, a || b after it fails.
  • A script's status is that of its last command or the number given to exit; timers and monitoring read it.
Ubuntu 24.04
Loading…