Patch-ID: bash40-021
[bash.git] / examples / scripts.v2 / bashrand
blob54260c0c254902bd0ecd067c29b25a90929a51a3
1 #! /bin/bash
2 # bashrand - generate a random number in a specified range with an
3 # optionally specified ``seed'' value.
5 # Original Author: Peter Turnbull, May 1993
7 usage()
9 echo "$PROG: usage: $PROG [-s seed] lower-limit upper-limit" >&2
12 PROG=${0##*/}
14 SEED=$$ # Initialize random-number seed value with PID
16 while getopts s: opt
18 case "$opt" in
19 s) SEED=$OPTARG ;;
20 *) usage ; exit 2 ;;
21 esac
22 done
24 shift $((OPTIND - 1))
26 # Process command-line arguments:
27 case $# in
28 2) Lower=$1; Upper=$2 ;;
29 *) usage ; exit 2 ;;
30 esac
32 # Check that specified values are integers:
33 expr "$Lower" + 0 >/dev/null 2>&1 || {
34 echo "$PROG: lower ($Lower) not an integer" >&2
35 exit 1
38 expr "$Upper" + 0 >/dev/null 2>&1 || {
39 echo "$PROG: upper ($Upper) not an integer" >&2
40 exit 1
43 expr "$SEED" + 0 >/dev/null 2>&1 || {
44 echo "$PROG: seed ($SEED) not an integer" >&2
45 exit 1
48 # Check that values are in the correct range:
49 (( $Lower < 0 )) || [ `expr "$Lower" : '.*'` -gt 5 ] && {
50 echo "$PROG: Lower limit ($Lower) out of range" >&2
51 exit 1
54 (( $Upper > 32767 )) || [ `expr "$Upper" : '.*'` -gt 5 ] && {
55 echo "$PROG: Upper limit ($Upper) out of range" >&2;
56 exit 1
59 (( $SEED < 0 )) || (( $SEED > 32767 )) || [ `expr "$SEED" : '.*'` -gt 5 ] && {
60 echo "$PROG: Seed value ($SEED) out of range (0 to 32767)" >&2
61 exit 1
64 (( $Upper <= $Lower )) && {
65 echo "$PROG: upper ($Upper) <= lower value ($Lower)" >&2
66 exit 1
69 # Seed the random-number generator:
70 RANDOM=$SEED
72 # Compute value, scaled within range:
73 let rand="$RANDOM % ($Upper - $Lower + 1) + $Lower"
75 # Report result:
76 echo $rand