如何在Bash中生成随机数字？

` `\$ echo \$((1 + RANDOM % 10)) 3` `

` `\$ dd if=/dev/urandom count=4 bs=1 | od -td` `

`\$RANDOM`是一个内部的Bash函数（不是一个常量），它返回一个范围为0 – 32767的伪随机整数。它不应该被用来产生一个encryption密钥。

` `\$ od -A n -td -N 1 /dev/urandom` `

` `echo \$RANDOM` `

` `awk 'BEGIN { # seed srand() for (i=1;i<=1000;i++){ print int(1 + rand() * 100) } }'` `

` `echo \$((RANDOM%10))` `

` `shuf -i 1-100000 -n 1` `

` `rand 10; echo \$RET` `

` `declare -ia RANDCACHE declare -i RET RAWRAND=\$(( (1<<32)-1 )) function rand(){ # pick a random number from 0 to N-1. Max N is 2^32 local -i N=\$1 [[ \${#RANDCACHE[*]} -eq 0 ]] && { RANDCACHE=( \$(od -An -tu4 -N1024 /dev/urandom) ); } # refill cache RET=\$(( (RANDCACHE[-1]*N+1)/RAWRAND )) # pull last random number and scale unset RANDCACHE[\${#RANDCACHE[*]}-1] # pop read random number }; # test by generating a lot of random numbers, then effectively place them in bins and count how many are in each bin. declare -ic; declare -ia BIN for (( c=0; c<100000; c++ )); do rand 10 BIN[RET]+=1 # add to bin to check distribution done for (( c=0; c<10; c++ )); do printf "%d %d\n" \$c \${BIN[c]} done` `

` `#!/bin/bash declare -ia RCACHE declare -i RET # return value declare -i ENT=2 # keep track of unused entropy as 2^(entropy) declare -i RND=RANDOM%ENT # a store for unused entropy - start with 1 bit declare -i BYTES=4 # size of unsigned random bytes returned by od declare -i BITS=8*BYTES # size of random data returned by od in bits declare -i CACHE=16 # number of random numbers to cache declare -i MAX=2**BITS # quantum of entropy per cached random number declare -ic function rand(){ # pick a random number from 0 to 2^BITS-1 [[ \${#RCACHE[*]} -eq 0 ]] && { RCACHE=( \$(od -An -tu\$BYTES -N\$CACHE /dev/urandom) ); } # refill cache - could use /dev/random if CACHE is small RET=\${RCACHE[-1]} # pull last random number and scale unset RCACHE[\${#RCACHE[*]}-1] # pop read random number }; function randBetween(){ local -i N=\$1 [[ ENT -lt N ]] && { # not enough entropy to supply ln(N)/ln(2) bits rand; RND=RET # get more random bits ENT=MAX # reset entropy } RET=RND%N # random number to return RND=RND/N # remaining randomness ENT=ENT/N # remaining entropy }; declare -ia BIN for (( c=0; c<100000; c++ )); do randBetween 10 BIN[RET]+=1 done for c in \${BIN[*]}; do echo \$c done` `

` `void get_random_bytes_arch(void* buf, int nbytes)` `

` `dd if=/dev/urandom count=4 bs=1 | od -td` `

` `me@mymachine:~/\$ x=\$(head -c 1 /dev/urandom > tmp && hexdump -d tmp | head -n 1 | cut -c13-15) && echo \$(( 10#\$x & 127 ))` `

` `echo \${RANDOM:0:1} # random number between 1 and 9 echo \${RANDOM:0:2} # random number between 1 and 99` `

` `#!/bin/bash random() { local range=\${1:-1} RAND=`od -t uI -N 4 /dev/urandom | awk '{print \$2}'` let "RAND=\$RAND%(\$range+1)" } n=10 while [ \$(( n -=1 )) -ge "0" ]; do random 500 echo "\$RAND" done` `

` `perl -e 'print int rand 10, "\n"; '` `