#!/bin/sh -u # A "while" loop reading user input - structured version with flag # Syntax: $0 number # Purpose: loop reading input until the user types the given number # # NOTE: This script fragment is incomplete - it does not follow all # the script guidelines set out in "script_style.txt". It also # contains some "Instructor-Style" comments that you must not use in # your own scripts. See script_style.txt for details. # # -IAN! idallen@idallen.ca # Use standard search path, friendly umask, ASCII collating and sorting. # Set the language and character set to be ASCII/C standard. # PATH=/bin:/usr/bin ; export PATH LC_COLLATE=C ; export LC_COLLATE LANG=C ; export LANG umask 022 # Missing step: should validate input first - what if no argument is given? # Loops that process input from the user pose a problem in shell # programming - the shell doesn't have a "do ... while" or "do ... # until" loop with a test at the bottom. One way to code this is to # prompt the user for the first guess before starting the loop; but, # that duplicates a lot of code. Below is one way of handling it without # code duplication, using a flag variable that is set at loop bottom. number="$1" count=0 guessed="false" while [ "$guessed" != "true" ] ; do let count=count+1 # Prompt (always on stderr) for the input number. # Quick-exit the script if the user types EOF at the prompt. # echo 1>&2 "Try $count. Enter a guess for the number:" read guess || exit 1 # Do some minimal validation of the input. # Missing step: should validate that input is an integer. # if [ -z "$guess" ] ; then echo 1>&2 "$0: Blank line - no guess - program exits" exit 1 fi if [ "$guess" -eq "$number" ] ; then guessed="true" else # Tell the user the guess didn't match; give a hint. # echo "$count. guess '$guess' does not match the number" [ "$guess" -lt "$number" ] && echo " ... Too low." [ "$guess" -gt "$number" ] && echo " ... Too high." fi done echo "You guesed the number: $number" echo "Tries: $count" # script exits with the good return status of the last command