Process substitution

We know that we can use a pipe to provide the output of a command as an input to another command. For example:

$ cat file.txt | less

Here, the cat command output—that is, the content of file.txt—is passed to the less command as an input. We can redirect the output of only one process (cat process in this example) as an input to another process.

We may need to feed the output of multiple processes as an input to another process. In such a case, process substitution is used. Process substitution allows a process to take the input from the output of one or more processes rather than a file.

The syntax of using process substitution is as follows:

To substitute input file(s) by list

<(list)

OR

To substitute output file(s) by list

>(list)

Here, list is a command or a pipeline of commands. Process substitution makes a list act like a file, which is done by giving list a name and then substituting that name in the command line.

Diffing the output of two processes

To compare two sets of data, we use the diff command. However, we know that the diff command takes two files as an input for producing diff. So, we will have to first save the two sets of data into two separate files and then run diff. Saving the content for diff adds extra steps, which is not good. To solve this problem, we can use the process substitution feature while performing diff.

For example, we want to know the hidden files in a directory. In a Linux and Unix-based system, files that starts with . (dot) are known as hidden files. To see the hidden files, the -a option is used with the ls command:

$ ls -l ~  # Long list home directory content excluding hidden files
$ ls -al ~   # Long list home directory content including hidden files

To get only the hidden files in a directory, run the diff command on the sorted output obtained from the preceding two commands:

$ diff  <(ls -l ~ | tr -s " " | sort -k9) <(ls -al ~ | tr -s " " | sort -k9)
Diffing the output of two processes

Here, we have fed the commands ls -l ~ | tr -s " " | sort -k9 and ls -al ~ | tr -s " " | sort -k9 as input data to the diff command instead of passing the two files.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.7.186