I tried to compare floating point number by -gt but it says that point expecting integer value. That means it can not handle floating point number . Then i tried the following code
我想用-gt比较两个浮点数大小,但屏幕却提示期望整数数值。
这就意味着-gt不能处理浮点数。接着我使用以下代码
1
2
3
4
5
6
7
|
chi_square=4
if
[
"$chi_square>3.84"
|
bc
]
then
echo
yes
else
echo
no
fi
|
但屏幕却输出以下错误信息:
1
2
3
|
line 3: [: missing `]'
File ] is unavailable.
no
|
Here the no is echoed but it should be yes. I think that's because of the error it's showing. can anybody help me.
这里,执行结果本该是yes,此刻却提示no。我认为或许与提示的错误信息有关,谁能帮帮我呢?
【解决办法】
1.使用bc
要想使用bc的话请参考以下用法:
1
2
3
4
5
6
7
8
|
chi_square=4
if
[[ $(
bc
-l <<<
"$chi_square>3.84"
) -
eq
1 ]];
then
echo
'yes'
else
echo
'no'
fi
或
if
[[ `
echo
"$chi_square > 3.84"
|
bc
` -
eq
1 ]] ;
then
echo
yes
;
else
echo
no ;
fi
|
可通过bc的man手册来查看,若表达式成立则返回1。
expr1 > expr2
The result is 1 if expr1 is strictly greater than expr2.
2.使用awk
Just use awk instead
1
2
3
4
5
|
$
awk
-
v
chi_square=4
'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'
yes
$
awk
-
v
chi_square=3
'BEGIN{print (chi_square > 3.84 ? "yes" : "no")}'
no
|
或许,你并不喜欢使用三目运算,我也提供了使用shell变量来解决此问题。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
$ chi_square=4
$
awk
-
v
chi_square=
"$chi_square"
'BEGIN{
if
(chi_square > 3.84) {
print
"yes"
}
else
{
print
"no"
}
}'
yes
或
$
echo
"$chi_square"
|
awk
'{
if
($0 > 3.84) {
print
"yes"
}
else
{
print
"no"
}
}'
yes
或者
$
echo
"$chi_square"
|
awk
'{print ($0 > 3.84 ? "yes" : "no")}'
yes
|
本文转自 xoyabc 51CTO博客,原文链接:http://blog.51cto.com/xoyabc/1747395,如需转载请自行联系原作者