What happens after bash replacing a direct process?

According to Wikipedia, โ€œProcess substitution can also be used to capture output, which usually goes to a file, and redirects it to process input." ( http://en.wikipedia.org/wiki/Process_substitution ).

So, in my opinion, this means that with the replacement of the process, I can take the output of command A and use it as input to command B. In other words, it's like a pipe (is this right?).

So, if this is true, and if I do this:

echo "test" >(wc) 

then I should expect to get the following:

 1 1 5 

because my understanding of the above command is similar to the following:

 $echo "test" > tmp $wc tmp 1 1 5 tmp 

except that I am not making a tmp file with a replacement process.

But instead, I get the following output:

 test /dev/fd/63 

This, obviously, indicates that my mental model is wrong. Where am I mistaken?

I understand the <(command) command. for instance

 $diff <(head file1) <(head file2) 

makes perfect sense. but not> (command).

+4
source share
2 answers

From Process Substitution

The list of processes starts with its input or output connected to the FIFO or some file in / dev / fd . The name of this file is passed as an argument to the current command as a result of the extension. If you use the form> (list), the entry in the file will contain the input for the list .

What happens to echo "test" >(wc) ?

File /dev/fd/63 is opened to connect the echo test with wc . wc starts with the login connected to /dev/fd/63 . Then the name of this file ( /dev/fd/63 ) is passed as an argument to the current command ( echo "test" ), resulting in echo "test" /dev/fd/63 . That's why you see

 test /dev/fd/63 

as a conclusion. wc expects input, but since echo not written to /dev/fd/63 , the counter will be 0 .

If you want this to work, you must create a script that takes the last argument and prints the first N-1 arguments to the last

 #! /bin/bash echo "${@:1:$(($# - 1))}" >${@: -1} 

When you call it

 bash script.sh test >(wc) 

you will see the expected result

 1 1 5 
+3
source

Your mental model is wrong in that you missed one important detail: replacing a process is not a redirect.

When you perform a redirect such as "echo test> tmp", an "echo test" is performed, and stdout (represented by ">") is sent to a file named "tmp". When you perform a substitution such as "echo test> (wc)", "wc" is executed, and "> (wc)" is replaced by the name of the file (or perhaps the name of the magic device) that can be read or written.

As stated on the Wikipedia page you contacted: โ€œUnder the hood, process substitution works by creating a named pipe and then substituting its name on the command line.โ€

If you look closely at the diff example above, you will see that the same thing also works there. After all, what are the "diff" arguments, but the file names on the command line?

+2
source

All Articles