今天這個例子是 用來驗證用戶輸入的參數(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 #// 這個有點巧妙,就是如果函數(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)用,注意這里加了引號。
標(biāo)簽:六盤水 丹東 百色 優(yōu)質(zhì)小號 滁州 武漢 自貢 鎮(zhèn)江
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《驗證用戶輸入的參數(shù)合法性的shell腳本》,本文關(guān)鍵詞 驗證,用戶,輸入,的,參數(shù),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。