Most of the time, you will only need to work with three file streams; the standard input, standard output, and standard error. However, if you need to read input from a file into a shell script, or to send output to one or more other files, you may want to open some more files and attach them to file descriptor numbers.
To open files for reading, use the exec command. exec causes the commands following it on the line to be executed immediately without invoking a sub-shell. The command to be execed overlays the shell process, and when it terminates control returns to the parent of the process that carried out the exec.
You can use exec to attach new files to the input and
output file descriptors of the current shell process. For example,
to open a file called newscript as standard input to the
current shell, use the following command:
newscript should be executable and contain the following line:
echo "Hello world!"In this case, exec forces newscript to be opened as standard input, then causes its contents to be executed.
To open file1, file2 and file3
for input as file descriptors 1, 4 and 5 respectively, use the
exec 1< file1 4< file2 5< file3
Note that there is an anomaly in the Korn shell when opening file descriptors using exec. Although the Bourne and Korn shells allow you to open any recognized file descriptor for input or output, the Korn shell closes them immediately after executing the command line (with the exception of file descriptors 0, 1 and 2: standard input, standard output, and standard error). The C shell does not allow you to redirect or attach file descriptors: this is one of its major shortcomings.