考虑以下shell脚本和后面的输出......
#!/bin/bash
RANDOM=5
for i in {0..9..1}
do
rand_val=$(awk -v rand_awk=$RANDOM 'BEGIN{print rand_awk;}')
echo "generated $RANDOM"
echo "generated in awk: $rand_val"
done
首先运行:
generated 18499
generated in awk: 9147
generated 9909
generated in awk: 20212
generated 24640
generated in awk: 24874
generated 15572
generated in awk: 2499
generated 5516
generated in awk: 10235
generated 17897
generated in awk: 8039
generated 19000
generated in awk: 26744
generated 12793
generated in awk: 2500
generated 27730
generated in awk: 20895
generated 5509
generated in awk: 887
第二轮:
generated 18499
generated in awk: 16728
generated 9909
generated in awk: 31548
generated 24640
generated in awk: 11705
generated 15572
generated in awk: 10184
generated 5516
generated in awk: 6024
generated 17897
generated in awk: 838
generated 19000
generated in awk: 20789
generated 12793
generated in awk: 3646
generated 27730
generated in awk: 21647
generated 5509
generated in awk: 18333
第三次运行:
generated 18499
generated in awk: 6725
generated 9909
generated in awk: 9301
generated 24640
generated in awk: 24364
generated 15572
generated in awk: 19016
generated 5516
generated in awk: 21737
generated 17897
generated in awk: 9027
generated 19000
generated in awk: 17942
generated 12793
generated in awk: 19478
generated 27730
generated in awk: 9555
generated 5509
generated in awk: 31563
在awk
语句内部,RANDOM
生成的数字不受种子(5)的影响。
我希望rand_val
也受RANDOM
得到的种子的影响,主要是因为我希望以可预测的方式使用awk
rand()
函数:< / p>
#!/bin/bash
RANDOM=5
RANGE=3
for i in {0..9..1}
do
rand_val=$(awk -v rand_awk=$RANDOM -v range=$RANGE 'BEGIN{srand(rand_awk); print rand()*range;}')
echo "generated in awk: $rand_val"
done
答案 0 :(得分:2)
我怀疑$(...)
创建子shell并且RANDOM
是一个特殊变量。一个小小的改动让你的第一个脚本能够始终如一地做出响应:
#!/bin/bash
RANDOM=5
for i in {0..9..1}
do
R=$RANDOM
rand_val=$(RANDOM=$R awk -v rand_awk=$R 'BEGIN{print rand_awk;}')
echo "generated $RANDOM"
echo "generated in awk: $rand_val"
done
我只是将$ RANDOM重新分配给另一个变量,而是将其传递给它。