驗(yàn)證用戶輸入的參數(shù)合法性的shell腳本
今天這個(gè)例子是 用來驗(yàn)證用戶輸入的參數(shù)的合法性的,程序并不復(fù)雜,如下所示:
#!/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 #// 這個(gè)有點(diǎn)巧妙,就是如果函數(shù)的返回值為1的話,則執(zhí)行
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:]是 大小寫字母及數(shù)字的意思,這里sed的作用是將非大小寫字母及數(shù)字過濾掉。
2) if ! validAlphaNum "$input" $input作為 函數(shù)的參數(shù)被調(diào)用,注意這里加了引號(hào)。
相關(guān)文章
利用shell刪除數(shù)據(jù)表中指定信息和字段對(duì)應(yīng)的文件
這篇文章主要介紹了利用shell刪除數(shù)據(jù)表中指定信息和字段對(duì)應(yīng)的文件,需要的朋友可以參考下2014-04-04
關(guān)于shell的幾個(gè)不為人知卻十分有用的命令分享
這篇文章主要介紹了關(guān)于shell的幾個(gè)不為人知卻十分有用的命令,需要的朋友可以參考下2016-03-03

