- 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 commandExit 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 ⚠️
$?is overwritten immediatelyfalse echo "hello" echo $?This prints
0(fromecho), not fromfalse.Always read
$?immediately after the commandfalse echo $? # correctIn pipelines:
cmd1 | cmd2 echo $?$?is the exit code ofcmd2, notcmd1.
Quick mental model
$?answers: “Did the last command succeed?”
0→ yes- non-zero → no