summaryrefslogtreecommitdiff
path: root/examples/scripts.v2/bashrand
diff options
context:
space:
mode:
Diffstat (limited to 'examples/scripts.v2/bashrand')
-rw-r--r--examples/scripts.v2/bashrand76
1 files changed, 76 insertions, 0 deletions
diff --git a/examples/scripts.v2/bashrand b/examples/scripts.v2/bashrand
new file mode 100644
index 0000000..54260c0
--- /dev/null
+++ b/examples/scripts.v2/bashrand
@@ -0,0 +1,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