I'm running a process and I'm counting the number of threads with

ps huH p <PID_OF_U_PROCESS> | wc -l

I can run this thread with watch like this;

watch -n 1 ps huH p <PID_OF_U_PROCESS> | wc -l

This will output the number of threads the process is running, but usually that number doesn't change.

How can I only print the new number to screen if it changed from the last time the command was run?

For example:

64 65 64 (a few minutes go by) 65



You could just pipe to uniq:

while ps -o nlwp= -p "$pid"; do sleep 1; done | uniq

watch is not capable of doing this directly. Although you can highlight differences in the command output (via option -d) or exit when the output changes (via option -g) it is not possible to display the output of more than one run. But you can achieve this via other common tools.

One of many possible solutions:

last=""; while true; do cur="$(ps h -o nlwp -p <PID>)"; if ! [ "$cur" = "$last" ]; then last="$cur"; echo "$(date) $cur"; fi; sleep 1; done

Or more readable:

while true
    cur="$(ps h -o nlwp -p <PID>)"
    if ! [ "$cur" = "$last" ]
        echo "$(date) $cur"
    sleep 1

Explanation: The ps option -o nlwp directly prints the number of threads, so you don't have to call wc -l. You can also use $(pidof programname) instead of <PID> in order to determine the process ID automatically. I also added the current date via $(date) which seems useful to me. If you don't like it then just remove it.

  • If you want it to clear the screen like watch, add a clear statement on a line before the echo. – cas Nov 5 '15 at 0:32
  • But then you won't see the previous thread count, defeating the whole purpose of not using watch directly. – scai Nov 5 '15 at 7:59

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.