将字符串转换为数字并存储在变量中。

huangapple go评论107阅读模式
英文:

Bash - Convert String to Number and Store in Variable

问题

我正在尝试将CPU温度存储在一个变量中。我不确定如何使用sed,所以我主要在使用grep。到目前为止,以下是我的尝试,但我遇到了语法错误。我还在比较过程中遇到了错误,但我认为这是因为CPUTEMP没有解析。

#!/bin/bash
#
CPUTEMP=$(/usr/bin/sensors k10temp-pci-00c3 | grep temp1 | awk '{print $2}' | grep -o '[0-9,.]\+')

if [ "$CPUTEMP" -le 40 ]; then
    echo "OK - CPU idle"
    exit 0
...
...
fi

我在这里做错了什么?谢谢!

英文:

I am trying to store CPU temperature in a variable. I am not sure how to use sed so I am mostly using grep. Here is what I have tried so far, but I am getting syntax error. I am also getting error during the comparison, but I thing it is because CPUTEMP is not resolving.

#!/bin/bash
#
CPUTEMP = $((/usr/bin/sensors k10temp-pci-00c3 | grep temp1 | awk '{print \$2}' | grep -o '[0-9,.]\+'))

if [ "$CPUTEMP" -le 40 ]; then
    echo "OK - CPU idle"
    exit 0
...
...
fi

What am I doing wrong here? Thank you!

答案1

得分: 0

我在线上阅读了一些内容,成功解决了我的问题。我的脚本中存在四个问题。

  1. 我使用了 $(( ... )) 而不是 $( ... )
  2. 在 = 前后有空格
  3. 不需要在 $2 前面加 \
  4. Bash 只能比较整数,但我的 CPUTEMP 变量包含浮点数。需要使用 bc 来解决。

以下是可工作的代码:

#!/bin/bash
#
CPUTEMP=$(/usr/bin/sensors k10temp-pci-00c3 | grep temp1 | awk '{print $2}' | grep -o '[0-9,.]\+')

if (( $(echo "$CPUTEMP <= 40" | bc -l) ))
then
    echo "OK - CPU idle"
    exit 0
...
...
fi

感谢大家的帮助!

英文:

I read some more online and was able to solve my problem. There were four problems in my script.

  1. I used $(( ... )) instead of $( ... )
  2. There were spaces before and after =
  3. No need for \ before $2

(all of these problems above are in the same line where CPUTEMP is assigned a value)

  1. Bash can only compare integers, but my CPUTEMP variable contains floating point number. Need bc for the workaround.

Here is the working code:

#!/bin/bash
#
CPUTEMP=$(/usr/bin/sensors k10temp-pci-00c3 | grep temp1 | awk &#39;{print $2}&#39; | grep -o &#39;[0-9,.]\+&#39;)

if (( $(echo &quot;$CPUTEMP &lt;= 40&quot; | bc -l) ))
then
    echo &quot;OK - CPU idle&quot;
    exit 0
...
...
fi

Thank you for your help guys!

huangapple
  • 本文由 发表于 2023年7月13日 11:28:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定