Fundamentals 5 min read

What Does $? Mean in Bash? Mastering Exit Status and Conditional Commands

This article explains the special shell variable $?, how it returns the exit status of the previous command, demonstrates its use with practical examples, and shows how to combine it with && and || for conditional execution in Linux scripts.

ITPUB
ITPUB
ITPUB
What Does $? Mean in Bash? Mastering Exit Status and Conditional Commands

The variable $? is a special shell variable that holds the exit status of the most recently executed command; a value of 0 indicates success, while any non‑zero number signals an error.

In the shell, variables are referenced with a leading $, so the exit status is accessed as $?. For example:

# test -e /tmp/a.txt; echo $?
0   // file exists, exit status 0

If /tmp/a.txt does not exist, the same command returns a non‑zero status (typically 1).

Another illustration:

# echo 'onmpw'
onmpw
# echo $?
0
# 1name=onmpw
-bash: 1name=onmpw: command not found
# echo $?
127   // error code
# echo $?
0     // the previous command (echo $?) succeeded

The exit status is essential for controlling command flow. By using the logical operators && (AND) and || (OR), scripts can execute subsequent commands based on whether the preceding command succeeded.

Example with && and ||:

# test -e /tmp/a.txt && echo 'Yes' || echo 'No'
Yes   // file exists, first command succeeds, so echo 'Yes' runs

If the file does not exist:

# test -e /tmp/b.txt && echo "Yes" || echo "No"
No    // first command fails, so the OR part runs

In these expressions, && proceeds to the right‑hand command only when the left‑hand command returns 0, while || proceeds when the left‑hand command returns a non‑zero status. Understanding $? together with these operators enables reliable conditional execution in shell scripts.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

ShellScriptingBashconditional executionexit status
ITPUB
Written by

ITPUB

Official ITPUB account sharing technical insights, community news, and exciting events.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.