This question comes from Pro Bash Programming by Chris Johnson at Chapter 2 Exercises 2:
Write a script, using $RANDOM, to write the following output both to a file and to a variable. The following numbers are only to show the format; your script should produce different numbers:
1988.2365
13798.14178
10081.134
3816.15098
Here is my solution:
printf -v var "%5d.%-5d\n" $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM $RANDOM > FILE
It seems that the output directly goes into var, FILE is empty.
My question is that is there a way to redirect standard output to a variable and a file at the same time?
You could write:
using the
teecommand to “split” standard-output, so that it goes both intoFILEand into a new standard-output that can be captured in your variable using command substitution.