2012-05-05 35 views
0

私はコマンドの出力を格納する変数を持っています。浮動小数点と比較するにはどうすればいいですか?Bashの比較

私はfooがファイル名である

x=$(tail -n 1 foo| cut -d ' ' -f2) 

if (($x < 0)); then ... 

をしています。具体的に。私は次のエラー

-0.08 < 0 : syntax error: invalid arithmetic operator (error token is "0.08 < 0") 

を得る上で、私は比較する必要がある値が-0.08ですが、エラー・トークンは、私がこのような比較のために何をすべき

違うのですか?やってオン

答えて

3

bashは浮動小数点算術演算をサポートしていません。
ただし、算術演算を行う外部プログラムであるbcを使用することはできます。 manページから

if (($(bc <<< "$x < 0"))); then 
    printf "%f is less than 0\n" "$x"; 
fi 

は:

関係演算子は

expr1 < expr2 
     The result is 1 if expr1 is strictly less than expr2. 

    expr1 <= expr2 
     The result is 1 if expr1 is less than or equal to expr2. 

    expr1 > expr2 
     The result is 1 if expr1 is strictly greater than expr2. 

    expr1 >= expr2 
     The result is 1 if expr1 is greater than or equal to expr2. 

    expr1 == expr2 
     The result is 1 if expr1 is equal to expr2. 

    expr1 != expr2 
     The result is 1 if expr1 is not equal to expr2. 


1もまた、浮動小数点演算をサポートしていawkを使用することができます。

0

kshが利用できる場合は、floatをサポートしているので、Bashの代わりにスクリプトを書くことができます。 Zshはフロートもサポートしています。

#!/usr/bin/ksh 
x=$(tail -n 1 foo| cut -d ' ' -f2) 

if ((x < 0)) 
then 
    echo "less than" 
fi