Last Updated : 15 Jul, 2025
In Linux, $? is a special variable that holds the last executed command's exit status or return value. It is commonly used to check whether the previous command was successful or encountered an error.
By convention:
This variable is particularly useful in shell scripts, as it allows conditional execution based on the outcome of previous commands.
SyntaxThe $? operator is automatically set after each command execution. To display its value:
echo $?Basic Example
If the last command was executed successfully, $? will return 0:
$ echo $?
0
If the last command failed, $? will return a non-zero value.
Working with "$?" operator 1. Default ValueIts default value is 0 when the system starts and no command has been executed yet. Even if the last command has not been successfully executed and the system is restarted, we get its value as 0 when the following command is entered into the terminal.
echo $?2. Return Status of the Last Executed Command
It returns the exit status of the last executed command. In the example mentioned below, There is no command as eccho in UNIX and hence the last process was not successfully executed. So $? stores a non-zero value which is the exit status of the last executed command.
eccho3. Checking File Existence with $?
echo $?
In the example mentioned below, If the file exists (can be either directory or file), then the return value by the "ls" command will be 0 (i.e, the command has been successfully executed) else it will display a number which is non-zero. The number depends on the program.
Referring to the image below, consider that by default "file" doesn't exist then $? stores a return value of 2 (the command was not successfully executed) but once created using touch it displays 0 as the ls command returns 0 since the file exists.
ls file4. Exit Status of True and False Commands
echo $?
touch file
echo $?
Also, when we enter simple true and false values in the terminal,it displays 0 as true does nothing but exits with a status code 0. But if we give false then 1 will get printed as false exits with status code 1.
trueConclusion
echo $?
false
echo $?
The $? operator is a valuable tool for checking the status of the last executed command, especially in scripting. Understanding how to interpret its values allows you to create more robust and error-tolerant scripts, as decisions can be made based on whether the previous command was successful or not.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4