Exit Statuses and Flow Control

In programming languages, functions and methods generally return a value. Unix processes are the same. At the point that they exit, they set an exit status that tells you something useful about what happened when the process ran.

This exit status is always a number between 0 and 255. Convention dictates that 0 indicates success and that anything greater than 0 indicates some sort of failure. Individual programs are allowed to use whichever non-zero codes they like for whichever purpose, though it’s common to find programs that simply set a status of 0 for success and 1 for all failure states.

After running a command, we can check the value of the exit status that it set by inspecting the $? variable:

 
user@computer:~ $ ​ls​​ ​​-l​​ ​​Pictures​​ ​​|​​ ​​grep​​ ​​hendrix
 
-rw-r--r-- 1 rob staff 6688 7 May 2015 hendrix.jpg
 
 
user@computer:~ $ ​echo​​ ​​$?
 
0
 
 
user@computer:~ $ ​ls​​ ​​-l​​ ​​Pictures​​ ​​|​​ ​​grep​​ ​​slartibartfast
 
 
user@computer:~ $ ​echo​​ ​​$?
 
1

Here the exit status is 0 when grep successfully found a match and 1 when it didn’t. We could then act on this knowledge, perhaps taking a different course of action depending on whether it matched.

We can do this flow control easily by using short-circuiting Booleans. For example:

 
user@computer:~ $ ​ls​​ ​​-l​​ ​​Pictures​​ ​​|​​ ​​grep​​ ​​-q​​ ​​hendrix​​ ​​&&​​ ​​echo​​ ​​"found"
 
found
 
 
user@computer:~ $ ​ls​​ ​​-l​​ ​​Pictures​​ ​​|​​ ​​grep​​ ​​-q​​ ​​slartibartfast​​ ​​||​​ ​​echo​​ ​​"not found"
 
not found

Here we use && to run a command only if grep finds a match, and || to run a command only if it doesn’t. (By passing the -q, or quiet, option to grep, we tell it to hide its normal output, so we see only the output from our echo command.)

These basics will allow us to progress from using our shell as a place to enter commands to using our shell as a programming environment and will give us enough knowledge to understand all of the various ways that the shell is used in this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.64.62