To avoid usage of a sub-shell

suggest change

One major aspect of process substitution is that it lets us avoid usage of a sub-shell when piping commands from the shell.

This can be demonstrated with a simple example below. I have the following files in my current folder:

$ find . -maxdepth 1 -type f -print
foo bar zoo foobar foozoo barzoo

If I pipe to a while/read loop that increments a counter as follows:

count=0
find . -maxdepth 1 -type f -print | while IFS= read -r _; do
    ((count++))
done

$count now does not contain 6, because it was modified in the sub-shell context. Any of the commands shown below are run in a sub-shell context and the scope of the variables used within are lost after the sub-shell terminates.

command &
command | command 
( command )

Process substitution will solve the problem by avoiding use the of pipe | operator as in

count=0
while IFS= read -r _; do
    ((count++))
done < <(find . -maxdepth 1 -type f -print)

This will retain the count variable value as no sub-shells are invoked.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents