You need to know whether the command you ran succeeded.
The shell variable $? will be set with a non-zero value if the command fails—provided that the programmer who wrote that command or shell script followed the established convention:
$ somecommand it works... $ echo $? 0 $ badcommand it fails... $ echo $? 1 $
The exit status of a command is kept in the shell variable referenced with $?. Its value can range from 0 to 255. When you write a shell script, it’s a good idea to have your script exit with a non-zero value if you encounter an error condition. (Just keep it below 255, or the numbers will wrap around.) You return an exit status with the exitstatement (e.g.,exit 1orexit 0). But be aware that you only get one shot at reading the exit status:
Why does the second time give us 0 as a result? Because the second time is reporting on the status of the immediately preceding echo command. The first time we typedecho $?it returned a1, which was the return value of badcommand. But the echo command itself succeeds, therefore the new, most-recent status is success (i.e., a0 value). So you only get one chance to check it. Therefore, many shell scripts will immediately assign the status to another shell variable, as in:
We can keep the value around in the variable$STATand check its value later on.
Although we’re showing this in command-line examples, the real use of variables like$?comes in writing scripts. You can usually see if a command worked or not if you are watching it run on your screen. But in a script, the commands may be running unattended.
One of the great features of bash is that the scripting language is identical to commands as you type them at a prompt in a terminal window. This makes it much easier to check out syntax and logic as you write your scripts.
The exit status is more often used in scripts, and often inifstatements, to take different actions depending on the success or failure of a command. Here’s a simple example for now, but we will revisit this topic in future recipes:
$ somecommand ... $ if (( $? )) ; then echo failed ; else echo OK; fi
Recipe 4.5, "Deciding Whether a Command Succeeds"
Recipe 4.8, "Displaying Error Messages When Failures Occur"