Using Multiple Redirects on One Line
Problem
You want to redirect output to several different places.
Solution
Use redirection with file numbers to open all the files that you want to use. For example:
$ divert 3> file.three 4> file.four 5> file.five 6> else.where $
where divert
might be a shell
script with various commands whose output you want to send to different
places. For example, you might write divert to contain lines like
this: echo option $OPTSTR >&5
.
That is, our divert shell script could direct its
output to various different descriptors which the invoking program can
send to different destinations.
Similarly, if divert was a C program
executable, you could actually write to descriptors 3, 4, 5, and 6
without any need for open()
calls.
Discussion
In an earlier recipe we explained that each file descriptor is
indicated by a number, starting at 0 (zero). So standard input is 0, out
is 1, and error is 2. That means that you could redirect standard output with the slightly more verbose
1>
(rather than a simple >)
followed by a filename, but there’s no need. The shorthand> is
fine. It also means that you can have the shell open up
any number of arbitrary file descriptors and have them set to write
various files so that the program that the shell then invokes from the
command line can use these opened file descriptors without further
ado.
While we don’t recommend this technique, it is intriguing.
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.