這個(gè)shell是來(lái)判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù)
實(shí)現(xiàn)代碼如下:
#!/bin/sh # validfloat -- Tests whether a number is a valid floating-point value. # Note that this script cannot accept scientific (1.304e5) notation. # To test whether an entered value is a valid floating-point number, we # need to split the value at the decimal point. We then test the first part # to see if it's a valid integer, then test the second part to see if it's a # valid >=0 integer, so -30.5 is valid, but -30.-8 isn't. . validint # Bourne shell notation to source the validint function validfloat() { fvalue="$1" if [ ! -z $(echo $fvalue | sed 's/[^.]//g') ] ; then decimalPart="$(echo $fvalue | cut -d. -f1)" fractionalPart="$(echo $fvalue | cut -d. -f2)" if [ ! -z $decimalPart ] ; then if ! validint "$decimalPart" "" "" ; then return 1 fi fi if [ "${fractionalPart%${fractionalPart#?}}" = "-" ] ; then echo "Invalid floating-point number: '-' not allowed \ after decimal point" >2 return 1 fi if [ "$fractionalPart" != "" ] ; then if ! validint "$fractionalPart" "0" "" ; then return 1 fi fi if [ "$decimalPart" = "-" -o -z "$decimalPart" ] ; then if [ -z $fractionalPart ] ; then echo "Invalid floating-point format." >2 ; return 1 fi fi else if [ "$fvalue" = "-" ] ; then echo "Invalid floating-point format." >2 ; return 1 fi if ! validint "$fvalue" "" "" ; then return 1 fi fi return 0 }
notice:
1): if [ ! -z $(echo $fvalue | sed 's/[^.]//g') ] 將輸入,以.分成整數(shù)和小數(shù)部分。
2):if [ "${fractionalPart%${fractionalPart#?}}" = "-" ] 判斷小數(shù)點(diǎn)后面如果接‘-'號(hào),這輸出字符不合法
3)接著的一些if語(yǔ)句就是判斷小數(shù)及整數(shù)部分合不合法
4)由于 valiint函數(shù)沒(méi)給出,腳本不能完全執(zhí)行,valiint函數(shù)是判斷字符串是否全為數(shù)字.
標(biāo)簽:自貢 武漢 丹東 鎮(zhèn)江 滁州 百色 六盤(pán)水 優(yōu)質(zhì)小號(hào)
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《linux shell實(shí)現(xiàn)判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù)》,本文關(guān)鍵詞 linux,shell,實(shí)現(xiàn),判斷,輸入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。