在 Bash Shell 脚本中生成 1 到 10 之间的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8988824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Generating random number between 1 and 10 in Bash Shell Script
提问by A15
How would I generate an inclusive random number between 1 to 10 in Bash Shell Script?
如何在 Bash Shell 脚本中生成 1 到 10 之间的包含随机数?
Would it be $(RANDOM 1+10)
?
会$(RANDOM 1+10)
吗?
回答by OrangeTux
$(( ( RANDOM % 10 ) + 1 ))
EDIT.Changed brackets into parenthesis according to the comment. http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting
编辑。根据评论将括号更改为括号。 http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting
回答by Reinstate Monica Please
Simplest solution would be to use tool which allows you to directly specify ranges, like gnushuf
最简单的解决方案是使用允许您直接指定范围的工具,例如gnushuf
shuf -i1-10 -n1
If you want to use $RANDOM
, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution
如果你想使用$RANDOM
,将 0...32767 中的最后 8 个数字扔掉会更精确,并将其视为 0...32759,因为采用 0...32767 mod 10 你得到以下分布
0-8 each: 3277
8-9 each: 3276
So, slightly slower but more precise would be
所以,稍微慢一点但更精确
while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done
回答by Abhijeet Rastogi
To generate random numbers with bash use the $RANDOM internal Bash function. Note that $RANDOM should not be used to generate an encryption key. $RANDOM is generated by using your current process ID (PID) and the current time/date as defined by the number of seconds elapsed since 1970.
要使用 bash 生成随机数,请使用 $RANDOM 内部 Bash 函数。请注意,不应使用 $RANDOM 来生成加密密钥。$RANDOM 是通过使用您当前的进程 ID (PID) 和由 1970 年以来经过的秒数定义的当前时间/日期生成的。
echo $RANDOM % 10 + 1 | bc
回答by choroba
You can also use /dev/urandom:
您还可以使用 /dev/urandom:
grep -m1 -ao '[0-9]' /dev/urandom | sed s/0/10/ | head -n1
回答by Thomas Bratt
To generate in the range: {0,..,9}
在范围内生成:{0,..,9}
r=$(( $RANDOM % 10 )); echo $r
r=$(( $RANDOM % 10 )); echo $r
To generate in the range: {40,..,49}
在范围内生成:{40,..,49}
r=$(( $RANDOM % 10 + 40 )); echo $r
r=$(( $RANDOM % 10 + 40 )); echo $r
回答by l0pan
Here is example of pseudo-random generator when neither $RANDOM nor /dev/urandom is available
这是 $RANDOM 和 /dev/urandom 都不可用时的伪随机生成器示例
echo $(date +%S) | grep -o .$ | sed s/0/10/
回声 $(日期 +%S) | grep -o .$ | sed s/0/10/