How to generate a random number within a range in Bash?
相关问题
- How to get the return code of a shell script in lu
- JQ: Select when attribute value exists in a bash a
- Unity - Get Random Color at Spawning
- Invoking Mirth Connect CLI with Powershell script
- Emacs shell: save commit message
相关文章
- 使用2台跳板机的情况下如何使用scp传文件
- In IntelliJ IDEA, how can I create a key binding t
- Check if directory exists on remote machine with s
- shell中反引号 `` 赋值变量问题
- How get the time in milliseconds in FreeBSD?
- why 48 bit seed in util Random class?
- Reverse four length of letters with sed in unix
- Launch interactive SSH bash session from PHP
Random number between 0 and 9 inclusive.
you can also get random number from awk
I have taken a few of these ideas and made a function that should perform quickly if lots of random numbers are required.
calling
od
is expensive if you need lots of random numbers. Instead I call it once and store 1024 random numbers from /dev/urandom. Whenrand
is called, the last random number is returned and scaled. It is then removed from cache. When cache is empty, another 1024 random numbers is read.Example:
Returns a random number in RET between 0 and 9 inclusive.
UPDATE: That does not work so well for all N. It also wastes random bits if used with small N. Noting that (in this case) a 32 bit random number has enough entropy for 9 random numbers between 0 and 9 (10*9=1,000,000,000 <= 2*32) we can extract multiple random numbers from each 32 random source value.
Try this from your shell:
Here,
-t d
specifies that the output format should be signed decimal;-N 1
says to read one byte from/dev/urandom
.You can also use shuf (available in coreutils).