UNIX Shells by Example (4th Edition)
| < Day Day Up > |
11.13. Standard I/O and Redirection
The Korn shell opens three files (called streams ) whenever a program is started: stdin , stdout , and stderr . Standard input normally comes from the keyboard and is associated with file descriptor 0. Standard output normally goes to the screen, file descriptor 1. Standard error normally goes to the screen, file descriptor 2. Standard input, output, and error can be redirected to or from a file. See Table 11.18 for a list of redirection operators. Table 11.18. Redirection
Example 11.63.
(The Command Line) 1 $ tr '[A-Z]' '[a-z]' < myfile # Redirect input 2 $ ls > lsfile # Redirect output $ cat lsfile dir1 dir2 file1 file2 file3 3 $ date >> lsfile # Redirect and append output $ cat lsfile dir1 dir2 file1 file2 file3 Mon Sept 20 12:57:22 PDT 2004 4 $ cc prog.c 2> errfile # Redirect error 5 $ find . name \*.c print > founditfile 2> /dev/null 6 $ find . name \*.c print > foundit 2>&1 7 $ print "File needs an argument" 1>&2 8 $ function usage { print "Usage: (The Command Line) 1 $ tr '[A-Z]' '[a-z]' < myfile # Redirect input 2 $ ls > lsfile # Redirect output $ cat lsfile dir1 dir2 file1 file2 file3 3 $ date >> lsfile # Redirect and append output $ cat lsfile dir1 dir2 file1 file2 file3 Mon Sept 20 12:57:22 PDT 2004 4 $ cc prog.c 2> errfile # Redirect error 5 $ find . “ name \*.c “print > founditfile 2> /dev/null 6 $ find . “name \*.c “print > foundit 2>&1 7 $ print "File needs an argument" 1>&2 8 $ function usage { print "Usage: $0 [-y] [-g] filename" 1>&2 ; exit 1; } [-y] [-g] filename" 1>&2 ; exit 1; }
EXPLANATION
11.13.1 The exec Command and Redirection
The exec command can be used to replace the current program with the one being exec ed. Another use for the exec command is to change standard output or input without creating a subshell. If a file is opened with exec , subsequent read commands will move the file pointer down the file a line at a time until end of file. The file must be closed to start reading from the beginning again. However, if using UNIX utilities such as cat and sort , the operating system closes the file after each command has completed. See Table 11.19 for exec functionality. Table 11.19. exec Commands
11.13.2 Redirection and the Child Shell
When the output of a command is redirected from the screen to a file, the Korn shell creates (forks) a child shell to rearrange the file descriptors, as shown in Figure 11.2. Figure 11.2. Redirection of standard output and errors.
|
| < Day Day Up > |