浮点数输入在整数验证的基础上,将小数通过小数点分割成两部分,进行验证。
#!/bin/bash
. validint
validfloat()
{
fvalue="$1"
if [ ! -z $(echo $fvalue | sed 's/[^.]//g') ] ; then
decimalPart="$(echo $fvalue | cut -d. -f1)"
fractionalPart="${fvalue#*\.}"
if [ ! -z $decimalPart ] ; then
if ! validint "$decimalPart" "" "" ; then
return 1
fi
fi
if [ "${fractionalPart%${fractionalPart#?}}" = "-" ] ; then
echo "Invalid floating-point number: '-' not allowed \
after decimal point" >&2
return 1
fi
if [ "$fractionalPart" != "" ] ; then
if ! validint "$fractionalPart" "0" "" ; then
return 1
fi
fi
else
if [ "$fvalue" = "-" ] ; then
echo "Invalid floating-point format." >&2 ; return 1
fi
if ! validint "$fvalue" "" "" ; then
return 1
fi
fi
return 0
}
if validfloat $1 ; then
echo "$1 is a valid floating-point value"
fi
exit 0