Checking Command Success with $?
The special parameter $? expands to the exit code of the most recently completed command. It is the direct way to read the number that lesson 116 described: 0 for success, anything else for failure. Because $? gives the exact value rather than just "succeeded or failed", it is the tool to use when a script needs to tell different kinds of failure apart, include the status in a message, or keep the result for later.
ls /etc/hostname > /dev/null
echo $?
ls /nonexistent
echo $?
0
ls: cannot access '/nonexistent': No such file or directory
2
How $? Works
After every command (a simple command, a pipeline, a compound command such as if or for, a function call), Bash stores its exit code. $? reads that stored value. The next command then replaces it with its own status.
That replacement is the single most important fact about $?. The value describes only the command that finished immediately before the expansion happens:
ls /nonexistent 2> /dev/null
echo "first: $?"
echo "second: $?"
first: 2
second: 0
The first echo reports the status of ls. The second echo reports the status of the first echo, which succeeded. Even a command whose only job is to display $? changes it afterwards.
The Overwrite Trap in Conditions
The replacement also happens inside tests. A common pattern looks reasonable but prints the wrong number:
grep -q gamma words.txt
if [ $? -ne 0 ]; then
echo "not found, status was $?"
fi
not found, status was 0
words.txt contains alpha and beta, so grep returned 1. The test [ $? -ne 0 ] correctly saw 1 and succeeded, and that success (0) is what $? holds inside the then branch. The original status is gone.
The fix is to copy $? into an ordinary variable immediately after the command, before anything else runs:
grep -q gamma words.txt
status=$?
if [ "$status" -ne 0 ]; then
echo "not found, status was $status"
fi
not found, status was 1
A plain assignment such as status=$? is itself a command, but it does not matter: by then the value has already been copied. Saving $? on the very next line is a habit worth forming whenever the number will be used more than once.
Testing $? with Different Syntax
$? is an integer, so any of the integer comparison forms from lesson 73 work:
false
if [ $? -ne 0 ]; then echo "failed (test)"; fi
false
if [[ $? -ne 0 ]]; then echo "failed ([[ ]])"; fi
false
if (( $? != 0 )); then echo "failed (( ))"; fi
failed (test)
failed ([[ ]])
failed (( ))
For several possible values, case (lesson 75) is clearer than a chain of elif tests:
grep -q beta nofile.txt 2> /dev/null
case $? in
0) echo "match" ;;
1) echo "no match" ;;
*) echo "error" ;;
esac
error
grep returned 2 because the file does not exist, which falls into the * branch.
When You Do Not Need $?
For the common question "did this command succeed?", testing the command directly is shorter and avoids the overwrite trap completely:
if grep -q beta words.txt; then
echo "found"
fi
This is equivalent to running grep and then testing [ $? -eq 0 ], because if already looks at the exit code of the command it runs. The same holds for while, until, && and ||:
grep -q gamma words.txt || echo "gamma is missing"
mkdir -p out && echo "folder ready"
gamma is missing
folder ready
Use $? when you need the actual number; use the command itself as the condition when you only need success or failure. Lesson 122 develops the if command style further.
Reading $? Inside if and else Branches
Inside a branch, $? still holds the status of the condition that was just tested, as long as nothing else has run in between:
if grep -q gamma words.txt; then
:
else
echo "else branch sees $?"
fi
else branch sees 1
This lets a branch report the exact failure without a separate variable, provided $? is the first thing used in it.
Negation with ! changes the picture. ! inverts the result, and the inverted value is what $? holds:
if ! grep -q gamma words.txt; then
echo "negated branch sees $?"
fi
negated branch sees 0
The real status of grep (1) is lost. When the exact code matters, run the command without ! and save the status first.
Capturing the Status of a Command That Is Also Used in a List
cmd || rc=$? records the status only when the command fails, which is a compact way to keep going and remember what happened. Set the variable to 0 first so that it is meaningful when the command succeeds:
rc=0
grep -q gamma words.txt || rc=$?
echo "rc=$rc"
rc=0
grep -q beta words.txt || rc=$?
echo "rc=$rc"
rc=1
rc=0
This form is also safe under set -e (lesson 119), because a command on the left of || does not end the script when it fails.
It is equally useful for error messages that include the status:
cp nofile.txt /tmp/backup.txt 2> /dev/null || echo "cp failed with status $?"
cp failed with status 1
$? and Command Substitution
A plain assignment from command substitution keeps the status of the command inside $( ) (lesson 48):
out=$(grep gamma words.txt)
echo "status: $?"
out=$(grep beta words.txt)
echo "status: $? out=$out"
status: 1
status: 0 out=beta
This makes it possible to capture output and check success in one step:
if out=$(grep beta words.txt); then
echo "got: $out"
fi
The status is lost when the assignment is written as an argument to a builtin such as local, export, declare or readonly. The builtin runs after the substitution and reports its own success:
f() {
local out=$(grep gamma words.txt)
echo "with local on the same line: $?"
}
g() {
local out
out=$(grep gamma words.txt)
echo "local declared first: $?"
}
f
g
export E=$(false); echo "export: $?"
with local on the same line: 0
local declared first: 1
export: 0
Declaring the variable on one line and assigning it on the next keeps the real status. Lesson 92 explained the same point for local.
$? and Pipelines
For a pipeline, $? holds the status of the last command only (lesson 61). The array variable PIPESTATUS holds one status per command:
grep gamma words.txt | sort
echo "PIPESTATUS: ${PIPESTATUS[*]}"
PIPESTATUS: 1 0
grep failed (1) and sort succeeded (0), so $? alone would have been 0. Like $?, PIPESTATUS is replaced by the next command, so copy it straight away if you need more than one element:
grep gamma words.txt | sort
statuses=("${PIPESTATUS[@]}")
echo "grep: ${statuses[0]}, sort: ${statuses[1]}"
grep: 1, sort: 0
For a simple command, PIPESTATUS has one element equal to $?. Lesson 120 shows set -o pipefail, which makes $? itself report failures from earlier commands in a pipeline.
$? and Functions
A function's status is the value given to return, or the status of its last command (lesson 90). The caller reads it through $? like any other command:
check_file() {
[ -r "$1" ] || return 3
return 0
}
check_file /nope
echo "check_file returned $?"
check_file returned 3
Inside a function, $? at the very beginning is the status of the command that ran before the call, which is rarely useful. Pass any value the function needs as an argument instead.
$? in Traps
In an EXIT trap (lesson 123), $? holds the status with which the shell is exiting, which lets cleanup code know whether the script failed:
bash -c 'trap "echo trap sees \$?" EXIT; false'
echo "script status: $?"
trap sees 1
script status: 1
The echo inside the trap succeeded, but the script still exited with 1: the trap does not replace the exit status unless it calls exit itself.
A Retry Loop Using Status Values
This loop tries a command up to five times and keeps the last status for the final report. flaky is a stand-in that fails twice and then succeeds:
attempt=0
flaky() {
(( ++attempt ))
[ "$attempt" -ge 3 ]
}
for i in 1 2 3 4 5; do
if flaky; then
echo "succeeded on attempt $i"
break
fi
echo "attempt $i failed"
done
attempt 1 failed
attempt 2 failed
succeeded on attempt 3
In a real script, flaky would be a network call or a command such as curl, and the loop would usually wait with sleep between attempts (lesson 168 checks websites with curl).
The examples were run with Bash 5.2.21, GNU grep 3.11 and GNU coreutils 9.4. Error messages are shown in their interactive form.