Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop - process substitution vs. here string with command substitution

Can someone please explain the difference between these two while loops:

while read test; do
echo $test
done <<< "$(seq 5)"

-

while read test; do
echo $test
done < <(seq 5)
like image 880
HTF Avatar asked Aug 24 '13 21:08

HTF


1 Answers

while read test; do
  echo $test
done <<< "$(seq 5)"

Execute seq 5, collecting the result into a temporary variable. Then execute the while loop, feeding it the collecting result.

while read test; do
  echo $test
done < <(seq 5)

Set up a subshell to execute seq 5 and connect its stdout to stdin. Then start the while loop. When it finishes, restore stdin.

What's the difference? For seq 5, practically nothing; however, it can still be made visible by changing seq 5 to seq 5; echo done generating sequence >&2. Then you can see that in the first case, the entire seq execution finishes before the while loop starts, while in the second case they execute in parallel.

$ while read n; do echo $n > /dev/stderr; done \
>       <<<"$(seq 5; echo done generating sequence >&2)"
done generating sequence
1
2
3
4
5
$ while read n; do echo $n > /dev/stderr; done \
>       < <(seq 5; echo done generating sequence >&2)
1
2
done generating sequence
3
4
5

If it were seq 10000000, the difference would be much clearer. The <<<"$(...) form would use a lot more memory in order to store the temporary string.

like image 129
rici Avatar answered Oct 06 '22 00:10

rici