Print correct MHz or GHZ number depends of CPU scaling

Viewed 173

I have this script to grab the current cpu speed of a RPi

cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq | awk '{if($NF+0>1000000)printf "%.1f GHz\n",$NF/10000; else printf "%.f MHz\n",$NF}'

Results in

pi@pi-hole:~ $ cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq | awk '{if($NF+0>1000000)printf "%.1f GHz\n",$NF/10000; else printf "%.f MHz\n",$NF}'
600000 MHz
pi@pi-hole:~ $ cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq | awk '{if($NF+0>1000000)printf "%.1f GHz\n",$NF/10000; else printf "%.f MHz\n",$NF}'
150.0 GHz

I want to convert/display the output as 600 MHz or 1.5 GHz (in order to fits 6 digits depends on scaling). I'm able to display always in MHz but when the CPU goes above 999 MHz it breaks my script layout due to a one more digit.

Sorry for the question but I'm a newbie with bash. Thanks!

1 Answers

With GNU awk:

awk 'length==6{printf("%.0f MHz\n", $0/10^3); next} length==7{printf("%.1f GHz\n", $0/10^6)}' /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq

Output:

600 MHz
750 MHz
1.0 GHz
1.5 GHz
Related