Explaining Exit Command and Exit Status in Bash
The aim of this page📝 is to describe exit and exit statuses in bash, in the form of my footnotes under the wonderful Advanced Bash-Scripting Guide > Exit and Exit Status
The exit command does 2 things
- terminates a script (just as in the C program)
- optionally, can return a value
exit <n>
therefore terminates a script and returns error code (see below)- n is a 1byte/8bit number (0–255)
The <n>
returned by the exit command is an exit status
- synonyms: return status; exit code
- successful execution of a command/script returns
0
- all non-zeros are error codes
- every script has an exit status
- every function within a script has an exit status
- exit status is derived from the last command from the script
- exit status is present for all these scenarios ..1. exit with the
exit
command ..2. exit without exit command (implicit) ..3. exit with theexit $?
command
$?
reads the exit status of the last executed command
- this is often used for case analysis
- my particular example is an attempt to authenticate at Hashicorp Vault and ..exit if this is not successful in 5 s ..print suggestion that a client is maybe not in the VPN is
$?
is124
- The command-specific exit status for the
timeout
command is specified at timeout(1) — Linux manual pages
124: if COMMAND times out, and −−preserve−status is not specified
- For more on timeout, see https://medium.com/p/3cf8298035bf
8 exit codes have reserved meanings and are general for all commands
— from Advanced Bash-Scripting Guide > Exit Codes With Special Meanings
In general, error codes are for bash — modern languages support exceptions and they should be used instead!
- And there are many attempts to simulate try/catch behavior in bash, too
- ..see e.g. shell — Is there a TRY CATCH command in Bash — Stack Overflow
- However, what seems to be the authoritative answer says
bash
does not abort the running execution in case something detects an error state (unless you set the-e
flag). Programming languages that offertry/catch
do this to inhibit a "bailing out" because of this special situation (hence typically called "exception"). In thebash
, instead, only the command in question will exit with an exit code greater than 0, indicating that error state. You can check for that of course, but since there is no automatic bailing out of anything, a try/catch does not make sense. It is just lacking that context
- in other words, bash does not crash — unless you tell it to with
set -e
which is a different story