对用户输入的判断的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)感觉想得挺周全的。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下