英文:
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
我在线上阅读了一些内容,成功解决了我的问题。我的脚本中存在四个问题。
- 我使用了 $(( ... )) 而不是 $( ... )
- 在 = 前后有空格
- 不需要在 $2 前面加 \
- 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.
- I used $(( ... )) instead of $( ... )
- There were spaces before and after =
- No need for \ before $2
(all of these problems above are in the same line where CPUTEMP is assigned a value)
- 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 '{print $2}' | grep -o '[0-9,.]\+')
if (( $(echo "$CPUTEMP <= 40" | bc -l) ))
then
echo "OK - CPU idle"
exit 0
...
...
fi
Thank you for your help guys!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论