#!/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作為 函數的參數被調用,注意這里加了引號。