考慮下面的shell腳本,後面的輸出時RANDOM`不是由種子確定...殼牌`和`awk`
#!/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()
功能的種子進行:
#!/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
您使用的是什麼版本的awk? gnu awk 4.1.3這裏每次都會產生相同的序列,而srand()也會可靠地改變它。不要指望bash和awk生成相同的數字,即使它們具有相同的種子。他們不使用相同的隨機生成器。 –
@MarcB如何檢查我的awk版本? –
非常類似於任何其他基於Unix的util。 'awk -v'。 –