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)
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With