1

I would like to use $RANDOM to create the following output and write it both to a file and to a variable all in one line.

123
24234
758
4893

My attempts are as follows, and none of them worked. I tried to redirect the standard output of printf to read and then redirecting to a file

$ read var < printf "%s\n" $RANDOM $RANDOM $RANDOM $RANDOM > file

I also tried piping the standard output of printf to read then redirecting to a file:

$ printf "%s\n" $RANDOM $RANDOM $RANDOM $RANDOM | read var > file

Could someone kindly help me understand where my issue is?

2 Answers 2

1

read is used to grab input and assign them to variables. It does not produce output, so redirection would simply produce an empty file.

You can use the tee command instead. It takes input from stdin, and writes output to stdout as well as one or more files.

Using tee and variable assignment, you could do:

$ variable=$(printf "%s " $RANDOM $RANDOM $RANDOM $RANDOM | tee variable.txt)

Note that I have used "%s ", because you have asked for the output to be on a single line.

Which then gives you:

$ echo $variable
31738 28009 6462 15565

$ cat variable.txt
31738 28009 6462 15565
2
  • I get this error -bash: syntax error near unexpected token `|' Commented Aug 22, 2020 at 5:42
  • 1
    Sorry, there was a typo. You need variable=$(printf... for the assignment. I have corrected the answer.
    – Haxiel
    Commented Aug 22, 2020 at 6:13
1

Just do:

var="$RANDOM
$RANDOM
$RANDOM
$RANDOM
$RANDOM"

printf '%s\n' "$var" > file

Or if you'd rather those numbers be elements of an array than the list being stored as newline delimited in a scalar variable:

var=("$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM" "$RANDOM")
printf '%s\n' "${var[@]}" > file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .