对用户输入的判断的shell实现代码
今天的案例是将对用户输入的判断的
#!/bin/sh
#validint--Validatesintegerinput,allowingnegativeintstoo.
functionvalidint
{
#Validatefirstfield.Thentestagainstminvalue$2and/or
#maxvalue$3iftheyaresupplied.Iftheyarenotsupplied,skipthesetests.
number="$1";min="$2";max="$3"
if[-z$number];then
echo"Youdidn'tenteranything.Unacceptable.">&2;return1
fi
if["${number%${number#?}}"="-"];then#isfirstchara'-'sign?
testvalue="${number#?}"#allbutfirstcharacter
else
testvalue="$number"
fi
nodigits="$(echo$testvalue|sed's/[[:digit:]]//g')"
if[!-z$nodigits];then
echo"Invalidnumberformat!Onlydigits,nocommas,spaces,etc.">&2
return1
fi
if[!-z$min];then
if["$number"-lt"$min"];then
echo"Yourvalueistoosmall:smallestacceptablevalueis$min">&2
return1
fi
fi
if[!-z$max];then
if["$number"-gt"$max"];then
echo"Yourvalueistoobig:largestacceptablevalueis$max">&2
return1
fi
fi
return0
}
ifvalidint"$1""$2""$3";then
echo"Thatinputisavalidintegervaluewithinyourconstraints"
fi
解析脚本:
1)number="$1";min="$2";max="$3"指用户的3个输入;
2)nodigits="$(echo$testvalue|sed's/[[:digit:]]//g')"为后面测试用户输入的是否全为数字做准备
3)ifvalidint"$1""$2""$3";then注意"$1""$2""$3"要加引号。
4)testvalue变量是为了过滤负数后测试输入是否全为数字的。
5)感觉想得挺周全的。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短