Process Substitution

A unique but rarely used feature of bash is process substitution. Let’s say that you had two versions of a program that produced large quantities of output. You want to see the differences between the output from each version. You could run the two programs, redirecting their output to files, and then use the cmp utility to see what the differences were.

Another way would be to use process substitution. There are two forms of this substitution. One is for input to a process: >(list); the other is for output from a process: <(list). list is a process that has its input or output connected to something via a named pipe. A named pipe is simply a temporary file that acts like a pipe with a name.

In our case, we could connect the outputs of the two programs to the input of cmp via named pipes:

cmp <(prog1) <(prog2)

prog1 and prog2 are run concurrently and connect their outputs to named pipes. cmp reads from each of the pipes and compares the information, printing any differences as it does so.

This chapter has covered a lot of territory. Here are some exercises that should help you make sure you have a firm grasp on the material. Don’t worry if you have trouble with the last one; it’s especially difficult.

  1. Write a shell script called pinfo that combines the jobs and ps commands by printing a list of jobs with their job numbers, corresponding process IDs, running times, and full commands.

  2. Take a non-trivial shell script and “bullet-proof” it with signal traps.

  3. Take a ...

Get Learning the bash Shell, Second Edition 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.