0

I want to display the calculation of the CPU load in percentage.

num2=$(uptime | grep "average:" | tr -d " " | cut -d ':' -f 5 | cut -d ',' -f 2)

percent=$((num2(*100)))
echo 'CPU percentage' $percent

Am I missing something?

  • Is that an actual typo of (*100) or a copy/paste typo? – Jeff Schaller Dec 28 '18 at 19:03
  • Nope that's what I think how it should be. – User101 Dec 28 '18 at 19:08
  • 1
    bash arithmetic uses infix notation, so you'd need $((num2 * 100)), if that's all that's stopping you – Jeff Schaller Dec 28 '18 at 19:10
  • it always shows up a syntax error: invalid arithmetic operator (error token is ".01") – User101 Dec 28 '18 at 19:25
  • That seems like an awfully long pipeline - at least on Linux, you might want to look at reading the value more directly from /proc/loadavg e.g. awk '{print "CPU percentage " $2*100}' < /proc/loadavg – steeldriver Dec 28 '18 at 19:26
0

You can pipe your calculation for percent into bc.

percent=$(echo "scale=0;$num2*100" | bc)

It'll give you a number like "41.00" you can cut that off the end with

percent=${percent%.*}
0

Your num2 value will be something like 0.41. bash can do integer calculations only, no floating. That's why we get an eror msg like

bash: 0.41 * 100 : syntax error: invalid arithmetic operator (error token is ".41 * 100 ")

Try removing the dots when using your tr -d statement. That would be equivalent to a multiplication by 100.

  • This should be a comment. An answer should explain how to solve the problem, not just the reason for the error. – Barmar Dec 28 '18 at 23:46
  • Thanks, @Barmar. Added a proposal to circumnavigate the error. – RudiC Dec 29 '18 at 8:44
  • 1
    What dots in the tr -d command? Show the command he should be writing instead. – Barmar Dec 30 '18 at 4:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.