I'd like to be able to get the number of thread per process in command-line and get the exact same number I can see via the Activity Monitor.

At the moment the IntelliJ IDEA process (PID 5235) has 266 Thread. I'd like to get this number but via a command line.

I've tried

lsof -p 5235 | wc -l

Any suggestions?


Try the following:

NUM=`ps M <pid> | wc -l` && echo $((NUM-1))

We subtract 1 from the line count because ps outputs a HEADER in the 1st line.

| improve this answer | |
  • (1) The output from wc -l is a single “word”; i.e., a (single ) non-null sequence of non-blank characters, possibly preceded and/or followed by whitespace.  What do you gain by piping it into xargs?  (I.e., won’t your command do the same thing if you leave off the | xargs?)  Are you doing it just to strip the leading and/or trailing whitespace?  Why bother?  expr will take care of that for you.   … (Cont’d) – Scott Jun 30 '17 at 6:49
  • (Cont’d) …  (2) Why are you subtracting one?  To exclude the header line from the count?  Good answers explain things like that. (3) I suppose using expr is OK, but it might be better to say NUM=$((NUM-1)) or ((NUM--)). Or you could just suppress the header by saying ps M -opid= <pid>. – Scott Jun 30 '17 at 6:50
  • @Scott: you're absolutely right. I did update the answer to include the your improvements. Thank you! The only thing I didn't include was the -opid= because it doesn't seem to work on macOS. If you still feel it could be better, feel free to update it or just leave another comment. – jweyrich Jun 30 '17 at 12:48

This also works:

ps M <pid> | wc -l
| improve this answer | |
  • As discussed in the comments under jweyrich’s answer, this will be too high by one, because it will count the ps header line.  Or do you have a rationale for believing that your answer is correct? – Scott Jun 30 '17 at 16:20

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.