Answers:
将种子值分配给 RANDOM
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$ bash -c 'RANDOM=640; echo $RANDOM $RANDOM $RANDOM'
28612 27230 24923
$
注意,使用了单引号。双引号运行违反外壳插值规则:
$ bash -c 'RANDOM=42; echo $RANDOM $RANDOM $RANDOM'
19081 17033 15269
$ RANDOM=42
$ bash -c "RANDOM=640; echo $RANDOM"
19081
$ bash -c "RANDOM=640; echo $RANDOM"
17033
$ bash -c "RANDOM=640; echo $RANDOM"
15269
$
因为它$RANDOM
是在bash -c ...
运行子进程之前由父外壳插入的。使用单引号关闭插值(如上所示),或者防止插值:
$ RANDOM=42
$ SEED_FOR_MY_GAME=640
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$ bash -c "RANDOM=$SEED_FOR_MY_GAME; echo \$RANDOM"
28612
$
手册中RANDOM
提到了此功能bash(1)
RANDOM Each time this parameter is referenced, a random integer between
0 and 32767 is generated. The sequence of random numbers may be
initialized by assigning a value to RANDOM. If RANDOM is unset,
it loses its special properties, even if it is subsequently
reset.
set -x; FOO=42; bash -c "FOO=999; echo $FOO"
。双引号允许将外壳替换$RANDOM
为外壳的随机变量。内部bash外壳只是在回显一个整数。
random=$(bash -c "RANDOM=$mac; echo $RANDOM")
bash -c 'RANDOM=42; echo "$RANDOM" "$RANDOM" "$RANDOM"'
。
random=$(bash -c "RANDOM=640; echo $RANDOM")
,不是每次都会返回相同的值吗?还是因为$(bash ...
不会将b视为bash的新实例?