假設我們只談論正面(基數爲10)整數...並且不包括逗號,指數表示法和前導加號(+)...
# test for ${NUMBER} containing anything other than digits 0-9
if [[ "${NUMBER}" = @(*[!0-9]*) ]]
then
echo "error: argument is not a positive number."
else
echo "success: argument is a positive number"
fi
顯然它會變得更有趣,因爲你剝離了什麼被定義爲*有效* positive number
的假設。
擴大對sqrt163提出的解決方案......一個簡單的功能,應該使我們能夠處理指數符號,浮點/真實數字與領先的加號(+),同時允許調用進程濾除關於語法錯誤的輸入共同的只是問題的消息......
$cat test.sh
#!/bin/ksh
NUMBER=$1
isnumber()
{
# following should generate a non-zero for negative and non-numerics,
# while allowing the parent process to filter out syntax errors
[[ "${1}" -gt 0 ]]
}
# direct isnumber() output to /dev/null since we're only interested
# in the return code, and we want to mask any syntax issues if
# isnumber() is called with a non-numeric argument; unfortunately,
# for a valid numeric that contains a comma (eg, NUMBER = 1,000)
# our isnumber() call will fail
if isnumber ${NUMBER} >/dev/null 2>&1
then
echo "${NUMBER} is a positive number"
else
echo "${NUMBER} is not a positive number"
fi
而且一些測試...
$ for s in 1 1.33 1e5 1e-4 +1 +1.65 +1e4 1,000 -1 -1.234 -1e5 -1,000 a b a1b ab1 1ab "a b c"
do
test.sh "$s"
done
1 is a positive number
1.33 is a positive number
1e5 is a positive number
1e-4 is a positive number
+1 is a positive number
+1.65 is a positive number
+1e4 is a positive number
1,000 is not a positive number
-1 is not a positive number
-1.234 is not a positive number
-1e5 is not a positive number
-1,000 is not a positive number
a is not a positive number
b is not a positive number
a1b is not a positive number
ab1 is not a positive number
1ab is not a positive number
a b c is not a positive number
這讓我們(我相信)取得一個或多個逗號,這可以通過使用任何適合你想象的方法去除逗號來處理。
你認爲什麼是有效的「正數」......只有整數?浮動/真實(例如,3.1415)?指數表示法(例如,1e + 5)?領先的'+'(例如+5)? – markp
是的,只有整數-1,2,3等 – T2true