linux shell實現(xiàn)判斷輸入的數(shù)字是否為合理的浮點數(shù)
這個shell是來判斷輸入的數(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ù)點后面如果接‘-'號,這輸出字符不合法
3)接著的一些if語句就是判斷小數(shù)及整數(shù)部分合不合法
4)由于 valiint函數(shù)沒給出,腳本不能完全執(zhí)行,valiint函數(shù)是判斷字符串是否全為數(shù)字.
相關(guān)文章
詳談Linux寫時拷貝技術(shù)(copy-on-write)必看篇
下面小編就為大家?guī)硪黄斦凩inux寫時拷貝技術(shù)(copy-on-write)必看篇。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07Linux下使用Shell腳本實現(xiàn)ftp的自動上傳下載的代碼小結(jié)
如何實現(xiàn)在ftp自動上傳下載文件腳本呢?想必還有很多朋友都不太了解吧,下面是ftp自動上傳下載文件腳本方法,希望對朋友們有些幫助2013-02-02利用Linux中的crontab實現(xiàn)分布式項目定時任務(wù)功能
crond是Linux用來定期執(zhí)行程序的命令.這篇文章主要介紹了利用Linux中的crontab實現(xiàn)分布式項目定時任務(wù),需要的朋友可以參考下2018-01-01