...

/

Process Substitution

Process Substitution

In this lesson, you will learn about process substitution, a handy way to save time and make scripts more concise and elegant. What you’ll learn will also allow you to capture the output of a command into a variable so that you can use it in other contexts or access it later.

How Important is this Lesson?

I spent years reading and writing bash before I understood this concept, so this lesson can be skipped. However, since I learned about process substitution, I use it on the command line almost every day, so I recommend you learn it at some point.

Simple Process Substitution

Type this in to set files up for this lesson:

Press + to interact
mkdir a
mkdir b
touch a/1 a/2 # Creates files 1 and 2 in folder a
touch b/2 b/3 # Creates files 2 and 3 in folder b
ls a
ls b
Terminal 1
Terminal
Loading...

You’ve created two folders with slightly different contents.

Now let’s say that you want to diff the output of ls a and ls b (a trivial but usefully simple example here). How would you do it?

Note: if you are not familiar with the diff command, you can find an introduction to it here.

You might do it like this:

Press + to interact
ls a > aout # List the files in the folder 'a' and redirect output to the 'aout' file
ls b > bout # List the files in the folder 'b' and redirect output to the 'bout' file
diff aout bout # Diff the two outputs
rm aout bout # Clean up the temporary output files

That works, and there’s nothing ...