代码之家  ›  专栏  ›  技术社区  ›  xinthose

如何从bash获得平均CPU温度?

  •  0
  • xinthose  · 技术社区  · 8 年前

    如何从Linux上的bash获得平均CPU温度?最好是华氏度。脚本应该能够处理不同数量的cpu。

    1 回复  |  直到 8 年前
        1
  •  1
  •   gmagno    6 年前

    您还可以直接从 sysfs (但是,不同计算机/操作系统之间的路径可能不同):

    temp_file=$(mktemp -t "temp-"$(date +'%Y%m%d@%H:%M:%S')"-XXXXXX")
    ls $temp_file
    while true; do
        cat /sys/class/thermal/thermal_zone*/temp | tr '\n' ' ' >> "$temp_file"
        printf "\n" >> $temp_file
        sleep 2
    done
    

    如果您是fish用户,可以向config dir添加一个函数,例如: ~/.config/fish/functions/temp.fish

    function temp
        set temp_file (mktemp -t "temp-"(date +'%Y%m%d@%H:%M:%S')"-XXXXXX")
        ls $temp_file
        while true
            cat /sys/class/thermal/thermal_zone*/temp | tr '\n' ' ' >> "$temp_file"
            printf "\n" >> $temp_file
            sleep 2
        end
    end
    

    例子

    enter image description here

        2
  •  0
  •   xinthose    6 年前

    你这样做:

    安装

    sudo apt install lm-sensors
    sudo sensors-detect --auto
    

    #!/bin/bash
    
    # 1. get temperature
    
    ## a. split response
    ## Core 0:       +143.6°F  (high = +186.8°F, crit = +212.0°F)
    IFS=')' read -ra core_temp_arr <<< $(sensors -f | grep '^Core\s[[:digit:]]\+:') #echo "${core_temp_arr[0]}"
    
    ## b. find cpu usage
    total_cpu_temp=0
    index=0
    for i in "${core_temp_arr[@]}"; do :
        temp=$(echo $i | sed -n 's/°F.*//; s/.*[+-]//; p; q')
        let index++
        total_cpu_temp=$(echo "$total_cpu_temp + $temp" | bc)
    done
    avg_cpu_temp=$(echo "scale=2; $total_cpu_temp / $index" | bc)
    
    ## c. build entry
    temp_status="CPU: $avg_cpu_temp F"
    echo $temp_status
    
    exit 0
    

    输出

    CPU:135.50华氏度

    推荐文章