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.

iTaMaR
  • 189
  • 2
  • 10
  • You could use [proc(5)](https://man7.org/linux/man-pages/man5/proc.5.html). BTW, processes are migrated by the kernel from one core to another – Basile Starynkevitch May 13 '21 at 19:18
  • In `[ ... ]`, you have to escape `>`, or it is interpreted as redirection, creating a file `95`. – Benjamin W. May 13 '21 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` – William Pursell May 13 '21 at 19:23
  • Use `if [ "$CPUcore1" -gt 95 ] && [ "$CPUcore2" -gt 95 ]` – William Pursell May 13 '21 at 19:24
  • Escaping the `\>` is not what you want, since that will do a lexical comparison rather than a numeric comparison. – William Pursell May 13 '21 at 19:27
  • LOL I get it, But thats not my question, I need the `CPUcore1` and `CPUcore2` calc.. – iTaMaR May 13 '21 at 19:28
  • It's hard to keep up with the edits! `( $CPUcore1 > 95 )` is also not what you want, since that will run the command `$CPUcore1` in a subhsell and redirect its output to a file named `95`. – William Pursell May 13 '21 at 19:28
  • I used to JS, but thats not my question.. I need the calc as mentioned, the rest is searchable and easy to fix LOL – iTaMaR May 13 '21 at 19:32

1 Answers1

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300