Published on

exit status $?

In shell (e.g. bash, sh, zsh), $? is a special variable that stores the exit status of the most recently executed command.


What $? means

  • $?exit code of the last command

  • Exit codes are integers:

    • 0 → success
    • non-zero → failure (different numbers mean different errors)

Simple examples

1️⃣ Check if a command succeeded

ls /etc
echo $?

Output:

0

Meaning: ls /etc ran successfully.


2️⃣ Check if a command failed

ls /not-exist
echo $?

Output:

2

Meaning: ls failed (directory doesn’t exist).


Typical usage in scripts

Conditional check

some_command
if [ $? -ne 0 ]; then
    echo "Command failed"
    exit 1
fi

Shorter, idiomatic form (preferred)

some_command || {
    echo "Command failed"
    exit 1
}

Important details ⚠️

  1. $? is overwritten immediately

    false
    echo "hello"
    echo $?
    

    This prints 0 (from echo), not from false.

  2. Always read $? immediately after the command

    false
    echo $?   # correct
    
  3. In pipelines:

    cmd1 | cmd2
    echo $?
    

    $? is the exit code of cmd2, not cmd1.


Quick mental model

$? answers: “Did the last command succeed?”

  • 0 → yes
  • non-zero → no