Skip to content

Commit f508a89

Browse files
Merge pull request #98 from iagotito/normalize-cpu-usage-width
Create function to normalize cpu usage width
2 parents 8d1a7fa + 698cbc2 commit f508a89

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

scripts/cpu_info.sh

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,32 @@ get_tmux_option() {
1414
fi
1515
}
1616

17+
# normalize the percentage string to always have a length of 5
18+
normalize_percent_len() {
19+
# the max length that the percent can reach, which happens for a two digit number with a decimal house: "99.9%"
20+
max_len=5
21+
percent_len=${#1}
22+
let diff_len=$max_len-$percent_len
23+
# if the diff_len is even, left will have 1 more space than right
24+
let left_spaces=($diff_len+1)/2
25+
let right_spaces=($diff_len)/2
26+
printf "%${left_spaces}s%s%${right_spaces}s\n" "" $1 ""
27+
}
28+
1729
get_percent()
1830
{
1931
case $(uname -s) in
2032
Linux)
2133
percent=$(LC_NUMERIC=en_US.UTF-8 top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1"%"}')
22-
echo $percent
34+
normalize_percent_len $percent
2335
;;
2436

2537
Darwin)
2638
cpuvalue=$(ps -A -o %cpu | awk -F. '{s+=$1} END {print s}')
2739
cpucores=$(sysctl -n hw.logicalcpu)
2840
cpuusage=$(( cpuvalue / cpucores ))
2941
percent="$cpuusage%"
30-
echo $percent
42+
normalize_percent_len $percent
3143
;;
3244

3345
CYGWIN*|MINGW32*|MSYS*|MINGW*)

0 commit comments

Comments
 (0)