Exit Codes

View saved

Zero means success

By convention, 0 is success and non-zero is failure. Many tools use specific codes.

true; echo $?
false; echo $?

Exit your script

exit N ends the script with status N. Ending without exit uses the last command's status.

if [[ ! -f "$1" ]]; then
  echo "not found: $1" >&2
  exit 1
fi

Pipe status

With pipes, $? is normally the last command. set -o pipefail makes the pipeline fail if any stage fails.

set -o pipefail
false | true
echo $?   # non-zero with pipefail

Useful conventions

  • 1 — general error
  • 2 — misuse / bad args (common for CLIs)
  • 127 — command not found
  • Print errors to stderr (>&2)

Comments

One comment per signed-in account. Comments are saved with this page’s URL.