0

I've already figured this out on Windows, but how to do it on Linux eludes me:

tasklist /V /NH | find "test test 123"

And then I count the number of non-empty lines in the output. This is super slow but works. Now I'm looking for the Linux method of doing the same.

That is, "test test 123" can be the full process title, it can begin with it, it can end with it, or just have it in the middle. This is important.

2 Answers2

2

TL;DR: use pgrep -cf "test test 123"


The ps program will list all running processes. Specifically, try:

ps aux 

Now, you could just filter that list using grep to search for your string:

ps aux | grep "test test 123"

That will print out matching lines. To count them, use grep -c which prints out the number of matching lines instead:

ps aux | grep -c "test test 123"

The problem with this approach is that the grep process above will also appear in the results. For example, I am currently editing a file named test test 123, but if I run the command above, I'll see both the process of my file editor and the grep itself:

$ ps aux | grep  "test test 123"
terdon   2461453 22.0  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
terdon   2462354  0.0  0.0   8832  2292 pts/1    S+   15:53   0:00 grep --color test test 123

Therefore, the grep -c will return 2 instead of 1:

$ ps aux | grep -c "test test 123"
2

Which brings us to the right tool for the job, pgrep. This is a tool specifically designed to find processes:

$ pgrep -cf "test test 123"
1

The -c means "count the matches" and the -f means "search the entire command line, not just the process name".

The other common trick to skip the grep itself is to use a one-character character class instead of the same string so that the grep command line won't contain the string:

$ ps aux | grep  "test test 123"
terdon   2461453  1.2  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
terdon   2476971  0.0  0.0   8832  2236 pts/1    S+   15:56   0:00 grep --color test test 123
$ ps aux | grep  "[t]est test 123"
terdon   2461453  1.2  0.2 392944 79796 pts/1    Sl   15:53   0:02 emacs test test 123
$ ps aux | grep -c "[t]est test 123"
1

For more on this trick see here. But this really isn't necessary if your system has pgrep as Linux systems do.

terdon
  • 242,166
0
echo $(( $(ps aux | grep "test test 123" | wc -l) - 1))

should to the trick

muaB
  • 31
  • See https://unix.stackexchange.com/a/578816/5132 and its further reading for the reasons that it won't. – JdeBP Apr 16 '20 at 15:54