#!/bin/bash
#initialize some variables
ans=0 # variable for digit being inputted.
sum=0 # sum of digits inputted.
urc=0 # storage for return code.
ask ()
{
#ask prompt user for a single digit other than 0.
# while user gives an invalid input,
# keep re-asking.
# If user issues a ctrl-c,
# then trap and return from ask with a code of 23
#
# valid digit will be stored in ans which is accessible
# in main code block.
# trap ctrl-c - INTR
# if ctrl-c entered while in this loop
# set return code of ask function to 23 and return.
#
# because 'while' tests actual return code of ask
# user needs to preserve a return code for later.
trap "urc=23; return 1;" 2
# grep test the string in $ans for NOT (-v) a single non-zero digit.
# while this is true
while echo "$ans" | grep -v "^[1-9q]$" >/dev/null 2>&1
do
# prompt user for a single digit.
echo -c "Input 1 digit 1-9 : "
# read input from user.
read ans
done
}
# invoke the ask to get a digit.
# ask won't return unless a valid digit or ctrl-c is issued.
while ask
do
# check for user return code 23 (ctrl-c used)
if [ "$urc" -eq 23 ]
then
# tell user and reset return code.
echo "interrupt detected"
# reset urc for next call of ask
urc=0
# go back to top of loop and ask again.
continue
fi
# process digit provided.
echo "you picked $ans"
# if user specified q - for quit. Then break out of ask loop.
if [ $ans = "q" ]
then
break
fi
sum=`expr $sum + $ans`
# check to see if sum is maxed (over 100)
if [ $sum -gt 100 ]
then
# if so, quit ask loop.
break
else
ans=0
fi
done
# show final total.
echo "sum = $sum"
|