Explaining Exit Command and Exit Status in Bash

Pavol Kutaj
2 min readFeb 6, 2023

--

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

  1. terminates a script (just as in the C program)
  2. 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 the exit $? 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 $? is 124

124: if COMMAND times out, and −−preserve−status is not specified

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!

bash does not abort the running execution in case something detects an error state (unless you set the -e flag). Programming languages that offer try/catch do this to inhibit a "bailing out" because of this special situation (hence typically called "exception"). In the bash, 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

LINKS

--

--

No responses yet