Why does $ RANDOM generate a similar sequence of values โ€‹โ€‹inside two for loops in a shell script?

Here's the script:

#!/bin/ksh (for k in $(seq 6); do echo $RANDOM; done) > a.txt (for k in $(seq 6); do echo $RANDOM; done) > b.txt echo a.txt cat a.txt echo b.txt cat b.txt 

And an example output:

 a.txt 9059 1263 29119 14797 5784 24389 b.txt 1263 29119 14797 5784 24389 26689 

Please note that the two sequences of generated numbers overlap (i.e. both contain the sequence 1263, 29119, 14797, 5784, 24389).

+4
source share
1 answer

RANDOMLY Simple random number generator. Each time a RANDOM is referenced, it is assigned the next number in a series of random numbers.
The meaning in the series can be established by assigning a RANDOM number (see Rand (3)).

This is because you wrapped your code in subshells. When the parent shell calls a subshell, it only takes into account one reference to $ RANDOM, although the for-loop uses it 6 times. When the parent shell calls the second subshell, it starts on the next number in a random sequence, so you see that your two output streams are disabled by one. If you remove the subshell, this behavior will disappear.

Try the following:

 for k in $(seq 6); do echo $RANDOM; done > a.txt for k in $(seq 6); do echo $RANDOM; done > b.txt 

Note: Bash does not have this behavior even with subshells.

+3
source

Source: https://habr.com/ru/post/1335295/


All Articles