开发者

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 of output:

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

Notice that the two sequences of numbers generated overlap (i.e., both contain the sequence 1263, 29119, 14797, 开发者_高级运维5784, 24389).


RANDOM A simple random number generator. Every time RANDOM is referenced, it is assigned the next number in a random number series.
The point in the series can be set by assigning a number to RANDOM (see rand(3)).

It is because you wrapped your code in subshells. When the parent shell calls the subshell, it only counts that as one reference to $RANDOM even though the for-loop uses it 6 times. When the parent shell calls the 2nd subshell, it starts at the next number in the random sequence which is why you see your two output streams off by one. If you remove the subshell's, this behavior goes away.

Try this:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜