1

According process substitution in bash, stdout of one command can be piped into several programs at once using the following template:

echo 'foobar' | tee >(command1) >(command2) | command3

So, you could do:

echo "the fox jumped over the lazy dog" | tee >(grep fox) >(grep jumped)

And get the output of all three commands.

Now I tried storing the output of all these commands, but with no success:

echo "the fox jumped over the lazy dog" | tee >(n1=$(grep fox)) >(n2=$(grep jumped))
echo $n1, $n2

You will see $n1 and $n2 are empty! Why? Is there a way to make this work?

Thank you.

user1527227
  • 2,068
  • 5
  • 25
  • 36
  • Since you're `grep`-ing a single line, n1 and n2 would just have same values. Is that intended? – konsolebox Jul 28 '14 at 18:36
  • A way to make this work is in the answers to this question: http://stackoverflow.com/q/12451278/3596168 – Scz Nov 15 '16 at 09:42

1 Answers1

1

For the same reason that the following outputs bar:

$ foo=bar
$ $(foo=quux)
$ echo $foo
bar

Assignments in sub-shells (or in your case entirely separate processes) do not make changes in the parent (or entirely unrelated) shell.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Thanks @EtanReisner. So what is the "proper method" of solving my problem? – user1527227 Jul 28 '14 at 18:19
  • If you need to send the same output to multiple commands and save all their outputs in the same shell session then you are going to need to save the output from the command and repeat it to each other command manually. `out=$(first command); n1=$(echo "$out" | second-command); n2=$(echo "$out" | third-command); ... "$n1" "$n2"`. – Etan Reisner Jul 28 '14 at 18:28
  • Do you know where in the documentation i can read about parent and subshells and whats passed between them? – user1527227 Jul 28 '14 at 19:06
  • 1
    The `Command Execution Environment` section of the bash man page talks about it some. But in general the sub-shell knows about most things from the parent shell and the parent shell knows nothing (other than output of and, potentially, the return code of the sub-shell). – Etan Reisner Jul 28 '14 at 19:17