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:
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.
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 wasecho FAIL, and the script's status is its zero: check with./check.sh; echo $?. -
7 is curl's status, but
echo FAILran 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 commandpicks a branch by that command's status;[ … ]is just such a command. -
a && bruns b after a succeeds,a || bafter it fails. -
A script's status is that of its last command or the number given to
exit; timers and monitoring read it.