Process Substitution
This trick allows you to use a process *almost* anywhere you can use a file. To illustrate, let's consider the
diff
command. Most versions of diff
require you to pass exactly two file names as arguments. But what if we want to diff something, like the contents of a directory, that doesn't necessarily exist in a file? This is where we can use process substitution. For example, to diff the contents of two directories, you could use:diff <(find dir1) <(find dir2)
The syntax
<(command)
creates a named pipe, and attaches command
's STDOUT to the pipe. So, anything that reads from the pipe will actually be reading the output of command. To prove this to yourself, try the following:$ echo <(/bin/true) /dev/fd/63 $ ls -l <(/bin/true) lr-x------ 1 jgm eng 64 Jul 13 21:50 /dev/fd/63 -> pipe:[31340331] $ file <(/bin/true) /dev/fd/63: broken symbolic link to pipe:[31340360]
Similarly, you can use the syntax
>(command)
to have the command
read from the pipe. An example is:tar cvf >(gzip -c > dir.tar.gz) dir
Obviously, there are better ways to accomplish taring and compressing, but the point was to use process substitution.
No comments:
Post a Comment