#!/bin/sh -u # Demonstrate a "while" loop # Syntax: $0 number # Purpose: loop reading input until the user types the number # # NOTE: This script fragment is incomplete - it does not follow all # the script guidelines set out in "script_style.txt". # # -IAN! idallen@idallen.ca # missing step: should validate input first # This is a value that we hope never matches the argument number. # It is used as a dummy value just to get the loop started the first time. # random=2845736 number="$1" guess="$random" count=0 while [ "$guess" -ne "$number" ] ; do let count=count+1 # Complain about previous guess; prompt and get next guess. # Don't complain the first time through the loop. # if [ "$count" -gt 1 ] ; then echo "$count. guess '$guess' does not match the number" fi 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 0 fi done echo "You guesed the number: $number" echo "Tries: $count" # script exits with the return status of the last command