Skip to main content
In Bash and other POSIX-compliant shells, the special variable $? holds the exit status of the last executed command, script, or function. Checking this value is essential for robust error handling in shell scripts.

Table of Contents

  1. Part 1: Using $?
  2. Part 2: Writing Scripts That Leverage $?
  3. References

Part 1: Using $?

What Is an Exit Status?

Every command returns an integer exit status.
  • 0 means success.
  • Non-zero indicates failure or a specific error condition.
The image explains that the special shell variable $? stores the exit status of a command, script, or function.
If you redirect both stdout and stderr (e.g., > /dev/null 2>&1), you won’t see any output, but $? still reflects success or failure.

Inspecting $? in Practice

  1. Script with a typo:
    Exit code 127 means “command not found.”
  2. Successful command:
  3. File-not-found error:

Common Exit Codes

The image shows a table of special shell variables with exit code numbers and their meanings, such as "0" for success and "1" for a general error."
You can define custom exit codes (128 and above) to represent specific failure modes in your scripts.

Back-to-Back Commands

When you execute multiple commands, $? always reflects the last exit status:

Masking Errors

A trailing exit 0 can hide earlier failures:

Part 2: Writing Scripts That Leverage $?

To ensure your script stops on errors and reports accurate statuses, apply one of these techniques.

Technique 1: if After Each Command

Technique 2: OR Operator (||)

Technique 3: set -e

Using set -e in an interactive shell will terminate your session on the first error.

Custom Exit Codes and a terminate Function

Initial Script: server_appender.sh

If fqdn.properties is empty, this outputs malformed hostnames.

Adding an Empty-File Check

Defining a terminate Function

By combining set -e, custom exit codes, and a reusable terminate function, your Bash scripts will halt on failures and report meaningful statuses.

References

Watch Video