Issue
The following short script prints a random ten-digit binary number:
#!/usr/bin/zsh
point=''
for i in `seq 1 10`
do
echo $RANDOM >/dev/null
point=$point`if [ $RANDOM -gt 16383 ]; then echo 0; else echo 1; fi`
done
echo $point
However, if I remove the apparently useless echo $RANDOM >/dev/null
line, the script always prints either 1111111111
or 0000000000
.
Why?
Solution
From the man page:
The values of RANDOM form an intentionally-repeatable pseudo-random sequence; subshells that reference RANDOM will result in identical pseudo-random values unless the value of RANDOM is referenced or seeded in the parent shell in between subshell invocations.
The "useless" call to echo
provides the reference that allows the subshell induced by the command substitution to produce a different value each time.
Answered By - chepner Answer Checked By - Senaida (WPSolving Volunteer)