“$?” is a variable that holds the return value of the last executed command. “echo $?” displays 0 if the last command has been successfully executed and displays a non-zero value if some error has occurred. The bash sets “$?” To the exit status of the last executed process. By convention 0 is a successful exit and non-zero indicates some kind of error. It can be used to check if the previous command has been executed without any errors. If it has executed successfully then it stores 0. “$?” is also useful in shell scripts as a way to decide what to do depending on how the last executed command worked by checking the exit status.
Working with “$?” operator
1. 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.
2. 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. 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. 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 $?