分类:
2008-03-21 16:51:13
我们之前在就提过一个问题,要检查的输入是否正确是一件极为简单的事情,但是要确认负数的值就有一定的困难了。进行的问题是:每一个数值只能够在开始的位置摆上一个负号。本节脚本的功能,在于确认负号的格式是否正确,以及检查使用者是否能够大小输入数值。
脚本源代码
#!/bin/sh
# validint -- Validates integer input, allowing negative ints too.
function validint
{
# Validate first field. Then test against min value $2 and/or
# max value $3 if they are supplied. If they are not supplied, skip these tests.
number="$1"; min="$2"; max="$3"
if [ -z $number ] ; then
echo "You didn't enter anything. Unacceptable." >&2 ; return 1
fi
if [ "${number%${number#?}}" = "-" ] ; then # is first char a '-' sign?
testvalue="${number#?}" # all but first character
else
testvalue="$number"
fi
nodigits="$(echo $testvalue | sed 's/[[:digit:]]//g')"
if [ ! -z $nodigits ] ; then
echo "Invalid number format! Only digits, no commas, spaces, etc." >&2
return 1
fi
if [ ! -z $min ] ; then
if [ "$number" -lt "$min" ] ; then
echo "Your value is too small: smallest acceptable value is $min" >&2
return 1
fi
fi
if [ ! -z $max ] ; then
if [ "$number" -gt "$max" ] ; then
echo "Your value is too big: largest acceptable value is $max" >&2
return 1
fi
fi
return 0
}
运行脚本
整个脚本程序是一个函数,它可以复制在其他程式码中或者像函数库一样加在其他档案里。在执行程式前,请把底下的几行程式加在先前代码的最末端:
if validint "$1" "$2" "$3" ; then
echo "That input is a valid integer value within your constraints"
fi
结果
$ validint 1234.3
Invalid number format! Only digits, no commas, spaces, etc.
$ validint 103 1 100
Your value is too big: largest acceptable value is 100
$ validint -17 0 25
Your value is too small: smallest acceptable value is 0
$ validint -17 -20 25
That input is a valid integer value within your constraints
改进与加强
我们比须了解如果数字的第一个位置是负号,它是如何做测试:
if [ "${number%${number#?}}" = "-" ] ; then
如果第一个字元是负号.那么程序会隔离负号並将testvalue的数值部份取出,取出的数值将会再分离并测试其中是否含有负号。你可以利用AND逻辑运算来运算并且打算减少回圈的话,以下面的改法来看,这似乎可以正常运作:
if [ ! -z $min -a "$number" -lt "$min" ] ; then
echo "Your value is too small: smallest acceptable value is $min" >&2
exit 1
fi
然而,它并沒有正常的运作,因为你不能保证:如果第一个运算失败了,AND逻辑运算将不会继续测试。从理论上来说.如果失败,它就不会继续测试,但是......