欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  网络运营

验证用户输入的参数合法性的shell脚本

程序员文章站 2022-08-26 16:10:25
今天这个例子是 用来验证用户输入的参数的合法性的,程序并不复杂,如下所示: #!/bin/sh # validalphanum - ensures that i...

今天这个例子是 用来验证用户输入的参数的合法性的,程序并不复杂,如下所示:

#!/bin/sh
# validalphanum - ensures that input consists only of alphabetical
# and numeric characters.

validalphanum()
{
 # validate arg: returns 0 if all upper+lower+digits, 1 otherwise

 # remove all unacceptable chars
 compressed="$(echo $1 | sed -e 's/[^[:alnum:]]//g')"

 if [ "$compressed" != "$input" ] ; then
  return 1
 else
  return 0
 fi
}

# sample usage of this function in a script

echo -n "enter input: "
read input

if ! validalphanum "$input" ; then  #// 这个有点巧妙,就是如果函数的返回值为1的话,则执行
 echo "your input must consist of only letters and numbers." >&2
 exit 1
else
 echo "input is valid."
fi

exit 0

就像上面所说这脚本流程和思路还是很简明的,就是讲你的输入用sed过滤后于原输入相比较,不相等则输入不合法。
值得注意的地方有
1) sed -e 's/[^ [:alnum:]]//g' ([:alnum:]是 大小写字母及数字的意思,这里sed的作用是将非大小写字母及数字过滤掉。
2) if ! validalphanum "$input" $input作为 函数的参数被调用,注意这里加了引号。