bash中与变量的浮点比较 [英] Floating point comparison with variable in bash
问题描述
我想将一个浮点变量与一个整数进行比较.我知道这对 bash 来说不是最好的,但是我的整个脚本已经用 bash 编写了.$number 可以是任何整数.如果它低于或等于 50,我想要 output1,对于所有其他人,我想要一个带有其他变量 k 的输出.这是我目前所拥有的:
I want to compare a floating point variable to an integer. I know this is not the best to do with bash, but my whole script is already written in bash. $number can be any integer. If it below or equal 50, I want output1, for all others I want an output with the other variable k. This is what I have so far:
number=43
test=$(echo "scale=2; $number/50" | bc -l)
echo "$test"
for k in {1..5}
do
if ["$test" -le 1]
then echo "output"
elif ["$test" -gt $k]
then echo "output$k"
fi
done
如果我尝试使用 test=0.43,第一个循环甚至不起作用.我认为它与整数和浮点比较有关,但无法使其工作.
If I try with test=0.43, the first loop does not even work. I think it has to do with an integer and a floating point comparison but cannot make it work.
有什么我遗漏的吗?
PS:这个[0.43: command not found
是终端输出的.
PS:this [0.43: command not found
is what the terminal outputs.
推荐答案
Bash 无法处理浮点数.改为管道到 bc
:
Bash can't handle floats. Pipe to bc
instead:
if [ $(echo " $test > $k" | bc) -eq 1 ]
您看到的错误是因为 test
命令(即 [
)前后需要空格
The error you see though is because the test
command (i.e. the [
) needs spaces before and after
使用 (( ... ))
会更好,因为您可以这样比较数字:
It is even better to use (( ... ))
since you compare numbers like this:
if (( $(bc <<< "$test > $k") ))
循环中的部分应该是这样的:
The part in the loop should look like this:
if (( $(bc <<< "$test <= 1") ))
then
echo "output"
elif (( $(bc <<< "$test > $k") ))
then
echo "output$k"
fi
关系表达式的值为 0,如果关系为假,则为 1,如果关系为真 [来源].但是请注意,这是 GNU bc
的一种行为,它不符合 POSIX
.
Relational expressions evaluate to 0, if the relation is false, and 1 if the relation is true [source]. Note however that is a behavior of GNU bc
, and it is not POSIX
compiant.
这篇关于bash中与变量的浮点比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!