0

I would like to listen to the CPU usage, by getting each core percentage usage: CPUcore1 and CPUcore2 in a loop.

while : do if [ $CPUcore1 -gt 95 ] && [ $CPUcore2 -gt 95 ] then //script.. fi done 

CPUcore1 and CPUcore2 should be equal to what present on htop

enter image description here

In this example:

CPUcore1=70.0

CPUcore2=44.4

I know that some calculation should be made in order to evaluate this.

8
  • You could use proc(5). BTW, processes are migrated by the kernel from one core to another Commented May 13, 2021 at 19:18
  • In [ ... ], you have to escape >, or it is interpreted as redirection, creating a file 95. Commented May 13, 2021 at 19:20
  • 1
    Fun fact: the command [ $CPUcore1 > 95 ] is semantically identical to test $CPUcore > 95 and > 95 test $CPUcore1 and test > 95 $CPUcore1 and [ > 95 $CPUcore1 ] and [ $CPUcore1 ] > 95 Commented May 13, 2021 at 19:23
  • Use if [ "$CPUcore1" -gt 95 ] && [ "$CPUcore2" -gt 95 ] Commented May 13, 2021 at 19:24
  • Escaping the \> is not what you want, since that will do a lexical comparison rather than a numeric comparison. Commented May 13, 2021 at 19:27

1 Answer 1

0

> is never what you want to compare numeric values. When it is a comparison operator, it is a lexical comparison rather than a numeric comparison. (so 2 > 10). Often, it's not a comparison operator, but a file redirect.

With test "$a" -gt "$b", $a and $b must be integers, and the string 70.0 is not an integer. Floating point arithmetic is ugly in the shell, so it's probably best to do it in awk with something like:

if awk -v a="$CPUcore1" -v b="$CPUcore2" 'BEGIN{exit !(a > 95 && b > 95)}'; then ... fi 
Sign up to request clarification or add additional context in comments.

5 Comments

I told u, thats not what I asked and yet you answered! Now no one will answer me since there is an answer..
@iTaMaR I don't understand your comment. You are attempting to do integer comparisons of non-integer values. If that's not the problem, I don't know what the problem is.
Ah....I see. ..
This code I posted was just an example for the wrapper of the variables I need, I need CPUcore1 and CPUcore2 calculations so that they will be equal to the usage of each core

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.