How to generate random number in Bash?

前端 未结 11 1489
青春惊慌失措
青春惊慌失措 2020-11-27 09:33

How to generate a random number within a range in Bash?

11条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 10:19

    Reading from /dev/random or /dev/urandom character special files is the way to go.

    These devices return truly random numbers when read and are designed to help application software choose secure keys for encryption. Such random numbers are extracted from an entropy pool that is contributed by various random events. {LDD3, Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman]

    These two files are interface to kernel randomization, in particular

    void get_random_bytes_arch(void* buf, int nbytes)
    

    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).

    dd if=/dev/urandom count=4 bs=1 | od -t d
    

    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:

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

提交回复
热议问题