I need to write script or command line code in Ubuntu which take CPU temperature and % of CPU usage from lm_sensors or something similar and this information I would like to save in .txt file with date and time of each measurement. I tried to write .sh file which is below, temperature works but CPU usage doesn’t work correctly it only save first measurement everytime. Can somebody help me?
while true; do echo $( date '+%H:%M:%S' ): $( sensors | grep 'CPU Temperature' | sed -r 's/^.*: +(.*) +[(].*$/1/' ) >> temperature.txt; echo $( date '+%H:%M:%S' ): $( top -b -n 1 | grep 'CPU:') >> cpu.txt; sleep 1; done
Advertisement
Answer
You can calculate the CPU usage as such, but only over time. The cpu usage isn’t stored in a file, you have to calculate it yourself:
cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) "%"}'
If you have a cpu temperature sensor, it’s located in /sys/class/hwmon
. You need to figure out yourself which one is correct, since that’s driver dependent. Mine is “coretemp”, I guess.
$ cat /sys/class/hwmon/hwmon*/name acpitz dell_smm coretemp nouveau
Once you found out the above, you can do the following:
#! /bin/bash LOG=cpu.log while true; do percentage=$(cat <(grep 'cpu ' /proc/stat) <(sleep 1 && grep 'cpu ' /proc/stat) | awk -v RS="" '{print ($13-$2+$15-$4)*100/($13-$2+$15-$4+$16-$5) "%"}') echo -n "$(date "+%F-%T") " >> ${LOG} echo -n "$percentage " >> ${LOG} cat /sys/class/hwmon/hwmon2/temp1_input >> ${LOG} done exit 0 `` [1] [Getting cpu usage same every time.](https://unix.stackexchange.com/questions/69185/getting-cpu-usage-same-every-time)