2015-01-06 83 views
0

爲了滿足功能要求,我必須檢索一個佔空比參數(0.01%的0-100%)。Bash整數表達式預計

用於測試,我寫的東西一樣簡單:

#!/bin/bash 
# 

if [ "$1" -lt 0 ] || [ "$1" -gt 100 ] 
then 
    echo "bad param" 
else 
    echo "ok" 
fi 

我獲得:

[email protected]:~# ./test.sh 11 
ok 
[email protected]:~# ./test.sh 11,01 
./test.sh: line 4: [: 11,01: integer expression expected 
./test.sh: line 4: [: 11,01: integer expression expected 
bad param 

如何實現這種測試的?

+2

我假設你使用','作爲小數點?正如你的錯誤告訴你的那樣,bash只支持整數。 –

+1

您將不得不使用'bc'(例如,請參閱http://stackoverflow.com/questions/12952427/bash-test-for-number-in-range-with-float-numbers) – fredtantini

+0

@SnP:您可以使用'awk'爲此。 – anubhava

回答

2

bash只能在整數運算中運算。如果你需要的花車,使用外部工具,如bc

if (($(bc <<< "($1 < 0) || ($1 > 100) "))) ; then 
    ... 
fi 

我寧願切換到一個更強大的語言對整個腳本,但(如Perl)/

+0

在[['中,而不是使用'-eq'或'(('' –

+0

@TomFenech:謝謝,只剩下試驗和錯誤:)' – choroba