#!/bin/sh -u # A "while" loop using numbers # Syntax: $0 number increment # # Loop counting down from $number by $increment. # # NOTE: This script fragment is incomplete - it does not follow all # the script guidelines set out in "script_style.txt". It also # contains many "Instructor-Style" comments that you must not use in # your own scripts. See script_style.txt for details. # # -IAN! idallen@idallen.ca # Validate the number of arguments before using any of them. # Tell the user (always on stderr) what was expected, and what was found. # if [ $# -ne 2 ] ; then echo 1>&2 "$0: expecting a number and increment, found $# ($*)" exit 1 fi # Transfer the arguments to variables with a readable names. # From this point on, use the readable names, not $1 and $2. # number="$1" increment="$2" # Test that $number and $increment are both numbers (not strings). # This is better done with a shell function; but, we do a simple version here. # We rely on the "test" command returning "2" for a non-numeric error. # (Normally "test" returns only 0 or 1.) We throw away error messages. # Bug: Invalid "octal" numbers (e.g. leading zero 09) pass unchecked. # test 2>/dev/null "$number" -eq 0 -a "$increment" -eq 0 if [ $? -eq 2 ] ; then # a status of 2 from "test" indicates a non-numeric error echo 1>&2 "$0: '$number' or '$increment' is not numeric" exit 1 fi # Make sure the increment is positive, non-zero. # if [ "$increment" -le 0 ] ; then echo 1>&2 "$0: increment must be > 0, found: $increment" exit 1 fi # Loop counting down from $number by $increment. # Note that variables don't need '$' in a "let" statement. # Bug: Invalid "octal" numbers (e.g. 09) will cause an infinite loop. # while [ "$number" -gt 0 ] ; do echo "number is $number" let number=number-increment done # Bug: In a "let" statement, bash treats numbers with leading zeroes as # octal, and it will complain and fail to execute if the octal number has # bad form, e.g. "x=09 ; let y=x" generates an error. This isn't true in # "test" statements, so you can't use a "test" statement to syntax-check an # octal number; you have to use a let statement. (But note that you can't # use a "let" statement to test for a non-numeric value; you have to use a # "test" statement.) It's messy.