Listing 4: getnum
##################################################
#
# getnum
#
# usage: getnum <min> <max> "<prompt>"
#
# obtain an integer from the user, and return it on standard
# output. Allow the user to abort by pressing return.
# Intended for use in shell scripts in conjunction with
# backquote substitution, as in:
#
# pick=`getnum 1 10 "Pick a number from 1 to 10"`
#
min=$1
max=$2
prompt=$3
while true
do
echo "$prompt [<return> to abort] > \c" >&2 # *see note 1
read n
[ "$n" = "" ] && echo "ABORT" && exit
if echo $1 $n $2 | awk '{ if (($1<=$2) && ($2<=$3)) exit 0 ;
else exit 1
}' # *see note 2
then
echo $n # return the number on stdout
exit
fi
done
#################################
#
# Notes:
#
# 1) The prompt is echoed to stderr rather than stdout, so that only the
# chosen number is returned on stdout.
#
# 2) Piping the number to awk is a simple way to make sure we have numbers
# since awk handles this for us. Note that if O is valid in the range of
# numbers (min to max), then a letter will count as zero.
#
|