aboutsummaryrefslogtreecommitdiffstats
path: root/examples/scripts.v2/bashrand
blob: 54260c0c254902bd0ecd067c29b25a90929a51a3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#! /bin/bash
# bashrand - generate a random number in a specified range with an
#	     optionally specified ``seed'' value.
#
# Original Author: Peter Turnbull, May 1993

usage()
{
	echo "$PROG: usage: $PROG [-s seed] lower-limit upper-limit" >&2
}

PROG=${0##*/}

SEED=$$         # Initialize random-number seed value with PID

while getopts s: opt
do
	case "$opt" in
	s)	SEED=$OPTARG ;;
	*)	usage ; exit 2 ;;
	esac
done

shift $((OPTIND - 1))

# Process command-line arguments:
case $# in
    2)  Lower=$1; Upper=$2 ;;
    *)  usage ; exit 2 ;;
esac

# Check that specified values are integers:
expr "$Lower" + 0 >/dev/null 2>&1 || {
	echo "$PROG: lower ($Lower) not an integer" >&2
	exit 1
}

expr "$Upper" + 0 >/dev/null 2>&1 || {
	echo "$PROG: upper ($Upper) not an integer" >&2
	exit 1
}

expr "$SEED" + 0 >/dev/null 2>&1 || {
	echo "$PROG: seed ($SEED) not an integer" >&2
	exit 1
}

# Check that values are in the correct range:
(( $Lower < 0 )) || [ `expr "$Lower" : '.*'` -gt 5 ] && {
	echo "$PROG: Lower limit ($Lower) out of range" >&2
	exit 1
}

(( $Upper > 32767 )) || [ `expr "$Upper" : '.*'` -gt 5 ] && {
	echo "$PROG: Upper limit ($Upper) out of range" >&2;
	exit 1
}

(( $SEED < 0 )) || (( $SEED > 32767 )) || [ `expr "$SEED" : '.*'` -gt 5 ] && {
	echo "$PROG: Seed value ($SEED) out of range (0 to 32767)" >&2
	exit 1
}

(( $Upper <= $Lower )) && {
	echo "$PROG: upper ($Upper) <= lower value ($Lower)" >&2
	exit 1
}

# Seed the random-number generator:
RANDOM=$SEED

# Compute value, scaled within range:
let rand="$RANDOM % ($Upper - $Lower + 1) + $Lower"

# Report result:
echo $rand