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
Use
$RANDOM
. It's often useful in combination with simple shell arithmetic. For instance, to generate a random number between 1 and 10:The actual generator is in
variables.c
, the functionbrand()
. Older versions were a simple linear generator. Version 4.0 ofbash
uses a generator with a citation to a 1985 paper, which presumably means it's a decent source of pseudorandom numbers. I wouldn't use it for a simulation (and certainly not for crypto), but it's probably adequate for basic scripting tasks.If you're doing something that requires serious random numbers you can use
/dev/random
or/dev/urandom
if they're available:I like this trick:
...
Please see
$RANDOM
:Reading from /dev/random or /dev/urandom character special files is the way to go.
These two files are interface to kernel randomization, in particular
which draws truly random bytes from hardware if such function is by hardware implemented (usually is), or it draws from entropy pool (comprised of timings between events like mouse and keyboard interrupts and other interrupts that are registered with SA_SAMPLE_RANDOM).
This works, but writes unneeded output from
dd
to stdout. The command below gives just the integer I need. I can even get specified number of random bits as I need by adjustment of the bitmask given to arithmetic expansion:There is $RANDOM. I don't know exactly how it works. But it works. For testing, you can do :
If you are using a linux system you can get a random number out of /dev/random or /dev/urandom. Be carefull /dev/random will block if there are not enough random numbers available. If you need speed over randomness use /dev/urandom.
These "files" will be filled with random numbers generated by the operating system. It depends on the implementation of /dev/random on your system if you get true or pseudo random numbers. True random numbers are generated with help form noise gathered from device drivers like mouse, hard drive, network.
You can get random numbers from the file with dd