When a program finishes, it returns a integer value. This code is known as the exit status or exit code. Depending on its value, we can see if the program terminated successfully or not.
If the value is
0, that means the program ran without a problem (this is why you return 0 in C programs). However, any value of
1 or greater means that it terminated unsuccessfully.
So...what do exit statuses have to do with control flow? Great question! We'll how all this ties in together real soon when we learn if-else statements.
To find the last exit status, simply use the
Be cautious in that if you run
echo $? twice in a row, the second command will always return a
0. Can you guess why?
Let's try some examples.
$ rm /; echo $? rm: /: is a directory 1 $ ls -l; echo $? # Lists folder contents 0 $ echo $? # Running 'echo $?' twice always produces a success 0
Here is a list of POSIX exit statuses.
$ ls -l hello_world # Not executable -rw-r--r-- 1 johnPC staff 0 Jul 3 09:41 hello_world $ ./hello_world -bash: ./hello_world: Permission denied $ echo $? 126 $ asdf $ echo $? 127
To terminate your script with a specific exit code, use the
exit code, followed by an integer.
if [ ! -e $SAMP_FILE ]; then exit 32 fi
if statements real soon, but this snippet simply checks if the file does not exist.
In some cases, a program can exit with a value other than
0, and still be considered a successful run.
For example, the
grep command returns a
0 if a matching pattern is found, and a
1 if no matching pattern is found. A value of
2 or greater is reported for real errors.
To ensure of no bugs in your code, make sure to check out a command's EXIT VALUE or DIAGNOSTICS section of its man page!
Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.$ Check price
Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.$$ Check price