对用户输入的判断的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)感觉想得挺周全的。
热门推荐
7 简短的二胎祝福语
10 简短霸气女儿生日 祝福语
11 祝福语高考小众诗句简短
12 元旦祝福语20秒简短
13 老师过年祝福语大全 简短
14 一生祝福语简短
15 产检祝福语简短霸气
16 朋友店开张祝福语简短
17 生日爱情祝福语大全简短
18 朋友女儿生日祝福语 简短