无法获取命令输出的绝对值
Unable to get the absolute value of command output
所以我想制作一个简单的脚本来继续检查我的 RasPi 的 CPU 温度,它存储在 /sys/class/thermal/thermal_zone0/temp
中,因此 cat /sys/class/thermal/thermal_zone0/temp
会给出温度,但是像这样:
cat /sys/class/thermal/thermal_zone0/temp
38459
这实际上意味着 38.459 摄氏度。
我无法格式化输出以获得 38.594 °C
我的代码:
tempT="$(cat /sys/class/thermal/thermal_zone0/temp)"
tempC=$($tempT / 1000)
echo "$tempC °C"
我得到的错误:
-bash: 38459: command not found
°C
谢谢
如果您的系统支持 bc,我会使用它。
$ CELSIUS=$(bc -l <<< $(cat /sys/class/thermal/thermal_zone0/temp)/1000)
$ echo $CELSIUS
25.00000000000000000000
最简单的方法是使用 awk
。
awk '{print /1000}' /sys/class/thermal/thermal_zone0/temp
或使用 printf
进行更多控制
awk '{printf "%.3f\n", /1000}' /sys/class/thermal/thermal_zone0/temp
您看到的错误来自于您使用了 $( ...)
,这是一个命令替换并试图 运行 里面的命令。所以当你这样做时:
$($tempT / 1000)
首先 $tempT
扩展为 38459,然后 shell 尝试 运行 一个名为 38459
的命令,带有两个参数 /
和 1000
.所以你看到消息 38459: Command not found
。使用 $((...))
进行算术扩展,但 shells 不实现浮点运算,因此您必须使用其他工具,如 awk
或 bc
.
TempC=$($tempT / 1000);
解析为:
TempC=$(38459 / 1000);
并且 bash 将 $(...)
视为要传递到子 shell 中的命令,因此它会尝试 运行 可执行文件 38455
,它找不到,因此抱怨。
我会按照@kinezan 的建议使用bc
,尽管我个人更喜欢以下约定:
TempC=$(echo "scale=3; $tempT / 1000" | bc)
输出38.459
所以我想制作一个简单的脚本来继续检查我的 RasPi 的 CPU 温度,它存储在 /sys/class/thermal/thermal_zone0/temp
中,因此 cat /sys/class/thermal/thermal_zone0/temp
会给出温度,但是像这样:
cat /sys/class/thermal/thermal_zone0/temp
38459
这实际上意味着 38.459 摄氏度。
我无法格式化输出以获得 38.594 °C
我的代码:
tempT="$(cat /sys/class/thermal/thermal_zone0/temp)"
tempC=$($tempT / 1000)
echo "$tempC °C"
我得到的错误:
-bash: 38459: command not found
°C
谢谢
如果您的系统支持 bc,我会使用它。
$ CELSIUS=$(bc -l <<< $(cat /sys/class/thermal/thermal_zone0/temp)/1000)
$ echo $CELSIUS
25.00000000000000000000
最简单的方法是使用 awk
。
awk '{print /1000}' /sys/class/thermal/thermal_zone0/temp
或使用 printf
进行更多控制awk '{printf "%.3f\n", /1000}' /sys/class/thermal/thermal_zone0/temp
您看到的错误来自于您使用了 $( ...)
,这是一个命令替换并试图 运行 里面的命令。所以当你这样做时:
$($tempT / 1000)
首先 $tempT
扩展为 38459,然后 shell 尝试 运行 一个名为 38459
的命令,带有两个参数 /
和 1000
.所以你看到消息 38459: Command not found
。使用 $((...))
进行算术扩展,但 shells 不实现浮点运算,因此您必须使用其他工具,如 awk
或 bc
.
TempC=$($tempT / 1000);
解析为:
TempC=$(38459 / 1000);
并且 bash 将 $(...)
视为要传递到子 shell 中的命令,因此它会尝试 运行 可执行文件 38455
,它找不到,因此抱怨。
我会按照@kinezan 的建议使用bc
,尽管我个人更喜欢以下约定:
TempC=$(echo "scale=3; $tempT / 1000" | bc)
输出38.459