linux shell實(shí)現(xiàn)判斷輸入的數(shù)字是否為合理的浮點(diǎn)數(shù)
這個(gè)shell是來判斷輸入的數(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語句就是判斷小數(shù)及整數(shù)部分合不合法
4)由于 valiint函數(shù)沒給出,腳本不能完全執(zhí)行,valiint函數(shù)是判斷字符串是否全為數(shù)字.
相關(guān)文章
linux下保留文件系統(tǒng)下剩余指定數(shù)目文件的shell腳本
本文介紹下,用于保留文件系統(tǒng)下剩余指定數(shù)量的文件的一個(gè)shell腳本,感興趣的朋友可以參考下2013-11-11
linux系統(tǒng)下用.sh文件執(zhí)行python命令的方法
這篇文章主要給大家介紹了關(guān)于linux系統(tǒng)下用.sh文件執(zhí)行python命令的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-07-07
詳解Linux中兩個(gè)查找命令locate和find教程
在linux中有很多查找命令,今天小編抽空給大家講解find和locate兩個(gè)命令,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-11-11
linux命令學(xué)習(xí)之10個(gè)網(wǎng)絡(luò)命令和監(jiān)控命令
下面列出來的10個(gè)基礎(chǔ)的每個(gè)linux用戶都應(yīng)該知道的網(wǎng)絡(luò)和監(jiān)控命令,大家參考使用吧2014-01-01
shell 使用數(shù)組作為函數(shù)參數(shù)的方法(詳解)
下面小編就為大家?guī)硪黄猻hell 使用數(shù)組作為函數(shù)參數(shù)的方法(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-04-04

