Solaris – Random Number Generation in Solaris

bashrandomshellshell-scriptsolaris

What is the best way to generate random numbers in Solaris?

I can not seem to find a good answer for this. Most results do not work in my environment. There is a variable or command RAND that seems logical it would work in some manner similar to $RANDOM which I see in most of my searches but it always produces 0.

I have found this command

od -X -A n /dev/random | head -2

Which seems very random but the return format is odd (to me).

     140774 147722 131645 061031 125411 053337 011722 165106
     066120 073123 040613 143651 040740 056675 061051 015211

Currently using:

-bash-3.2$ uname -a
SunOS XXXXXXXXX 5.10 Generic_150400-29 sun4v sparc SUNW,SPARC-Enterprise-T5120

Best Answer

$RANDOM is available in ksh and in bash, but not in /bin/sh. The value is a random number between 0 and 32768, and is not suitable for cryptographic use.

Reading from /dev/random generates a stream of random bytes which is suitable for cryptographic use. Since these are arbitrary bytes, potentially including null bytes, you can't store them in a shell variable. You can store $n bytes in a file with

</dev/random dd ibs=1 count=$n >rnd

You can use od to transform these bytes into a printable representation using octal or hexadecimal values. If you find the output “strange”, well, maybe you should pick different od options.

Another option to obtain a printable representation is to call uuencode to produce Base64:

</dev/random dd ibs=1 count=$n | uuencode -m _ | sed -e '1d' -e '$d'
Related Question