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.
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 0If /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 $?) succeededThe 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' runsIf the file does not exist:
# test -e /tmp/b.txt && echo "Yes" || echo "No"
No // first command fails, so the OR part runsIn 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
