Telling If a Command Succeeded or Not
Problem
You need to know whether the command you ran succeeded.
Solution
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 $
Discussion
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 exit statement
(e.g., exit 1 or exit 0). But be aware that you only get one
shot at reading the exit status:
$ badcommand it fails... $ echo $? 1 $ echo $? 0 $
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 typed echo $? it returned
a 1, which was the return value of
bad command. But the echo
command itself succeeds, therefore the new, most-recent status is
success (i.e., a 0 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:
$ badcommand it fails... $ STAT=$? $ echo $STAT 1 $ echo $STAT 1 $
We can keep the value around in the variable $STAT and
check its value later on.
Although ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access