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)?

220284
  • 141

1 Answers1

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.

terdon
  • 242,166