Section 5.9. Sequences


[Page 178 (continued)]

5.9. Sequences

If you enter a series of simple commands or pipelines separated by semicolons, the shell will execute them in sequence, from left to right. This facility is useful for type-ahead (and think-ahead) addicts who like to specify an entire sequence of actions at once. Here's an example:

$ date; pwd; ls        ...execute three commands in sequence. Wed Feb  2 00:11:10 CST 2005 /home/glass/wild a.c   b.c   cc.c  dir1  dir2 $ _ 



[Page 179]

Each command in a sequence may be individually I/O redirected:

$ date > date.txt; ls; pwd > pwd.txt a.c       b.c       cc.c      date.txt  dir1      dir2 $ cat date.txt              ...look at output of date. Wed Feb  2 00:12:16 CST 2005 $ cat pwd.txt               ...look at output of pwd. /home/glass $ _ 


5.9.1. Conditional Sequences

Every Linux process terminates with an exit value. By convention, an exit value of 0 means that the process completed successfully, and a nonzero exit value indicates failure. All built-in shell commands return 1 if they fail. You may construct sequences that make use of this exit value:

  • If you specify a series of commands separated by && tokens, the next command is executed only if the previous command returns an exit code of 0.

  • If you specify a series of commands separated by || tokens, the next command is executed only if the previous command returns a nonzero exit code.

The && and || metacharacters therefore mirror the operation of their counterpart C operators.

For example, if the C compiler gcc compiles a program without fatal errors, it creates an executable program called "a.out" and returns an exit code of 0; otherwise, it returns a nonzero exit code. The following conditional sequence compiles a program called "myprog.c" and only executes the "a.out" file if the compilation succeeds:

$ gcc myprog.c && a.out 


The following example compiles a program called "myprog.c" and displays an error message if the compilation fails:

$ gcc myprog.c || echo compilation failed. 


Exit codes are discussed in more detail toward the end of this chapter.




Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net