5.9. SequencesIf 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 $ _ 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 SequencesEvery 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:
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. |