Exit Status($?) variable in Linux
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:
- A return value of 0 indicates successful execution.
- Any non-zero value indicates an error or unsuccessful execution.
This variable is particularly useful in shell scripts, as it allows conditional execution based on the outcome of previous commands.
Syntax
The $? 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 Value
Its 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.
eccho
echo $?

3. Checking File Existence with $?
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 file
echo $?
touch file
echo $?

4. Exit Status of True and False Commands
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.
true
echo $?
false
echo $?

Conclusion
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.