Checking Command Success with $?

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 117 of 205

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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Checking Command Success with $? and get answers drawn from it.

Signed-in readers only.