Friday, May 09, 2008

Shell Based Random Number Generator

I observed a a few searches in my metadata stats for a shell based random generator. I know Korn, Bash, and Z Shell shells support a RANDOM variable. Depending on the shell, I will use a print and/or echo command to output its value. The pseudo-random generator outputs an integer between 0 and 32767 - yes, a very limited range. Here are a few examples for these three different shells.

Korn Shell
# ksh
# echo $RANDOM
23508
# echo $RANDOM
22618
# echo $RANDOM
1864
# echo $RANDOM $RANDOM
4958 29989
# print $RANDOM
30418
# print $RANDOM
4992
# print $RANDOM $RANDOM $RANDOM
29436 27342 12946

Seed the sequence of numbers
# RANDOM=100
# print $RANDOM
12662
# echo $RANDOM
23392
# RANDOM=100
# echo $RANDOM
12662
# echo $RANDOM
23392

Bash Shell
# bash
# echo $RANDOM
3107
# echo $RANDOM
7897

Z Shell
# zsh
# print $RANDOM
32274
# for i in {1..10}
for> do
for> print $RANDOM
for> done
10740
12659
9498
2798
3541
10384
21216
15221
22157
15198

Seed the sequence of numbers
# RANDOM=`date '+%H%S'`
# echo $RANDOM
12488
# echo $RANDOM
5266

No comments: