From 698cbc219106bf163fa8328cb2dbe8c723dba949 Mon Sep 17 00:00:00 2001 From: Iago Tito Oliveira Date: Sat, 27 Mar 2021 15:41:07 -0300 Subject: [PATCH] create function to normalize cpu usage width --- scripts/cpu_info.sh | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/scripts/cpu_info.sh b/scripts/cpu_info.sh index 9b845ef..6a5cec1 100755 --- a/scripts/cpu_info.sh +++ b/scripts/cpu_info.sh @@ -14,12 +14,24 @@ get_tmux_option() { fi } +# normalize the percentage string to always have a length of 5 +normalize_percent_len() { + # the max length that the percent can reach, which happens for a two digit number with a decimal house: "99.9%" + max_len=5 + percent_len=${#1} + let diff_len=$max_len-$percent_len + # if the diff_len is even, left will have 1 more space than right + let left_spaces=($diff_len+1)/2 + let right_spaces=($diff_len)/2 + printf "%${left_spaces}s%s%${right_spaces}s\n" "" $1 "" +} + get_percent() { case $(uname -s) in Linux) percent=$(LC_NUMERIC=en_US.UTF-8 top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}') - echo $percent + normalize_percent_len $percent ;; Darwin) @@ -27,7 +39,7 @@ get_percent() cpucores=$(sysctl -n hw.logicalcpu) cpuusage=$(( cpuvalue / cpucores )) percent="$cpuusage%" - echo $percent + normalize_percent_len $percent ;; CYGWIN*|MINGW32*|MSYS*|MINGW*)