1

I am on macOS. I want to write a bash script which pauses for 0.5 seconds (i.e. sleeps) while a certain process (which I know by command name only) uses more than, say 5% CPU. I could

pgrep command_name

and then

ps -p PID -o %cpu | tail -1 | cut -c 3-5

to get the CPU usage and use this number in a while loop. Can this be done more elegantly (ideally in one line of code)?

5
  • Sure you want to use CPU usage from ps? I.e. man ps | less +/'NOTES' and unix.stackexchange.com/q/58539/140633 Commented Jul 5, 2021 at 14:49
  • Happy to use top. But I still can't do it elegantly. Commented Jul 5, 2021 at 15:01
  • pidof might also be a good tool instead of pgrep. Commented Jul 5, 2021 at 16:37
  • by the way, what's the process you're watching there? (And: I don't know how or how much OS X smooths the CPU load, but this looks like something that might go wrong when your script happens to look in the wrong moments, when the process is e.g. limited by IO load) Commented Jul 5, 2021 at 16:39
  • I want to watch the app Apple Compressor Commented Jul 5, 2021 at 19:45

1 Answer 1

1

You can make it simpler by using command substitution:

ps -p $(pgrep firefox) -o %cpu | tail -1 | cut -c 3-5

I am afraid I don't have a mac to test on, so the following might not work on your system, but on Linux, we can use %cpu= to avoid printing the header:

$ ps -p $(pgrep firefox) -o %cpu 
%CPU
23.3
$ ps -p $(pgrep firefox) -o %cpu= 
23.3

Which means that ps -p $(pgrep firefox) -o %cpu= is enough to give you the number only.

3
  • @220284 you're welcome. Out of curiosity, which one worked? Does the = trick work with your ps? Commented Jul 5, 2021 at 20:55
  • ps -p $(pgrep firefox) -o %cpu= works on macOS as well Commented Jul 6, 2021 at 8:25
  • Ah good, I was afraid that was a GNU thing. Thanks! Commented Jul 6, 2021 at 8:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.