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.

3
  • Use the unix commands ps and grep in place of tasklist and find. You'll have to use the appropriate command line arguments as well. Commented Apr 16, 2020 at 14:33
  • To count lines, make a final pipe to wc -l Commented Apr 16, 2020 at 14:34
  • Windows have titles. Processes have accounting names and argument strings. You should decide which you are actually scanning. Commented Apr 16, 2020 at 14:42

2 Answers 2

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.

0
echo $(( $(ps aux | grep "test test 123" | wc -l) - 1)) 

should to the trick

1

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.