【问题标题】:How to compare decimal numbers in shell script?如何比较shell脚本中的十进制数字?
【发布时间】:2014-11-05 05:50:44
【问题描述】:
#!/bin/bash
for input in $(cat status_cpu.txt)
do
      cpu=`ssh -i  root@$input 'top -b -n1' | grep "load" | awk '{print $12}'`

      max=2.02

if [ $(echo "$cpu < $max" | bc -l ) ]; then
    echo "yes"
else
    echo "no" 
fi
done  

猫状态_cpu.txt
10.0.0.1
10.0.0.2

我想在 shell 脚本中比较小数点。

【问题讨论】:

  • FWIW,使用uptimetop 更容易获得系统负载...

标签: bash shell awk bc


【解决方案1】:

您不需要在同一行中使用 awkgrepawk 可以完成所有工作。
不要使用旧的和过时的反引号,使用括号。

所以这会改变:

cpu=`ssh -i  root@$input 'top -b -n1' | grep "load" | awk '{print $12}'`

收件人:

cpu=$(ssh -i  root@$input 'top -b -n1' | awk '/load/ {print $12}')

还有这个:

if [ $(echo "$cpu < $max" | bc -l ) ]; then
    echo "yes"
else
    echo "no" 
fi

可以写

[ $(echo "$cpu < $max" | bc -l ) ] && echo "yes" || echo "no"

[[ $(echo "$cpu < $max" | bc -l ) ]] && echo "yes" || echo "no"

【讨论】:

  • 对我最有帮助的答案,尽管我必须在 [] if 语句中添加 -eq 1;否则即使退出代码为 0,它也会进入 if。
【解决方案2】:

您可以像这样使用bc -l 进行比较:

max='2.02'
s='2.01'

bc -l <<< "$max > $s"
1

s='2.05'
bc -l <<< "$max > $s"
0

所以bc -l 表达式将打印 1 表示成功,0 表示失败。

【讨论】:

  • 这是在bash 中测试的,请确保您使用的是bash shell。否则使用管道:echo "$max &gt; $s" | bc -l
  • 如果您需要帮助,请花一些时间输入并首先提供有关您的环境的所有信息。你用的是什么外壳?你的bc 是什么版本?您尝试了什么命令,遇到了什么错误?
  • if [ $(echo "$cpu
  • 应该是:if [ $(echo "$cpu &lt; $max" | bc -l ) = 1 ]; then echo "yes"; else echo "no"; fi,你必须在bc命令之前使用echo "[$cpu]"检查$cpu的值。
【解决方案3】:

以下是如何将其放入 Posix shell 函数中,该函数随后可轻松用于 shell 测试(可能 bc 保留错误代码的返回代码):

ifbc () { test $(echo "$@" | bc -l ) -ne 0; }

以及此函数的示例用法:

ifbc "$max > $s" && echo "true, it's greater" || echo "no, it's less or ="

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多