example No. 1 作为shell编写人员,要避免使用者输入数据的格式不正确,也就是要在shell脚本发布前拦截可能的错误;本示例是对使用者输入的数据(或位置变量)进行判断是否可用,然后在符合条件时调用代码块;
#!/bin/bash
#shell name: shell_vaild.sh
#used:输入密码后判断密码是否是由数字和字母组成,判断输入的IP是否合法等
#author by woon
#定义函数
vaild_pass()
{
decide=$(echo $1 | sed -e "s/[^[:alnum:]]//g")
if [ "$decide" != "$pass" ];then
return 1
else
return 0
fi
}
#
read -t 10 -p "Please input IP address:" ipaddr
read -s -p "Please input the password:" pass
echo
#判断输入是否为空;空退出程序
if [ -z $ipaddr] || [ -z $pass ];then
echo "输入错误\n"
exit 2
fi
if ! vaild_pass "$pass";then
echo "Your inpur must consist of only letters and numbers.">&2
else
echo "Your password is vaild!"
fi
yn=$(echo $ipaddr|awk -F "." '{if($1<255&&$2<255&&$3<255&&$4<255){print "0"}else{print "1"}}')
if [ $yn == "0" ];then
echo "Your Ipaddr is vaild"
else
echo "Your IPADDR is not vaild."
exit 1
fi