简体   繁体   English

重击比较

[英]Bash comparison

I have a variable which stores the output of a command. 我有一个变量,用于存储命令的输出。 How do I compare it with a float? 如何与浮点数进行比较?

To be more specific I am doing 更具体地说,我在做

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

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

where foo is a filename. 其中foo是文件名。 On doing the above I get the following error 在执行上述操作时,出现以下错误

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

The value I need to compare is -0.08 , but the error token is different 我需要比较的值是-0.08 ,但错误令牌不同

What should I do for such comparisons? 我应该怎么做这样的比较?

bash doesn't support floating point arithmetics. bash不支持浮点运算。
You can however use bc which is an external program to do arithmetics. 但是,您可以使用外部程序bc进行算术运算。

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

from the man page: 从手册页:

The relational operators are 关系运算符是

  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. 

one can also use awk that also supports floating point arithmetics. 也可以使用还支持浮点运算的awk

If ksh is available to you, you can use it to write your script instead of Bash since it supports floats. 如果您可以使用ksh,则可以使用它而不是Bash来编写脚本,因为它支持浮点数。 Zsh also supports floats. Zsh还支持浮点数。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM