Patch-ID: bash40-021
[bash.git] / examples / scripts / krand.bash
blobdfdfd323b3ae63839526d629c91efd5b5a401ee4
1 # Originally
3 # From: bsh20858@news.fhda.edu (Brian S Hiles)
4 # Newsgroups: comp.unix.shell
5 # Subject: Re: getting random numbers
6 # Date: 23 Jan 1997 23:27:30 GMT
7 # Message-ID: <5c8s52$eif@tiptoe.fhda.edu>
9 # @(#) krand Produces a random number within integer limits
10 # "krand" Korn shell script generates a random number in a
11 # specified range with an optionally specified ``seed'' value.
12 # Author: Peter Turnbull, May 1993
13 # Modified by: Becca Thomas, January 1994
15 # changed the optional third argument to a -s option, converted to
16 # bash v2 syntax -- chet@po.cwru.edu
18 PROGNAME=${0##*/}
19 USAGE="usage: $PROGNAME [-s seed] lower-limit upper-limit"
21 Seed=$$ # Initialize random-number seed value with PID
23 usage()
25 echo ${PROGNAME}: "$USAGE" >&2
28 errexit()
30 echo ${PROGNAME}: "$@" >&2
31 exit 1
34 # Process command-line arguments:
35 while getopts "s:" opt; do
36 case "$opt" in
37 s) Seed=$OPTARG ;;
38 *) usage ; exit 2;;
39 esac
40 done
42 shift $(($OPTIND - 1))
44 case $# in
45 2) Lower=$1; Upper=$2 ;;
46 *) usage ; exit 2;;
47 esac
49 # Check that specified values are integers:
50 expr "$Lower" + 0 >/dev/null 2>&1
51 [ $? -eq 2 ] && { errexit "lower ($Lower) not an integer"; }
52 expr "$Upper" + 0 >/dev/null 2>&1
53 [ $? -eq 2 ] && { errexit "upper ($Upper) not an integer"; }
54 expr "$Seed" + 0 >/dev/null 2>&1
55 [ $? -eq 2 ] && { errexit "seed ($Seed) not an integer"; }
57 # Check that values are in the correct range:
58 if (( "$Lower" < 0 )) || [ ${#Lower} -gt 5 ]; then
59 errexit "lower limit ($Lower) less than zero"
61 if (( "$Upper" > 32767 )) || [ ${#Upper} -gt 5 ]; then
62 errexit "upper limit ($Upper) greater than 32767"
64 if (( "$Seed" < 0 )) || (( "$Seed" > 32767 )) || [ ${#Seed} -gt 5 ]; then
65 errexit "seed value ($Seed) out of range (0 to 32767)"
67 (( "$Upper" <= "$Lower" )) && errexit "upper limit ($Upper) <= lower limit ($Lower)"
69 # Seed the random-number generator:
70 RANDOM=$Seed
71 # Compute value, scaled within range:
72 let rand="$RANDOM % ($Upper - $Lower + 1) + $Lower"
73 # Report result:
74 echo $rand