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.
ps
andgrep
in place oftasklist
andfind
. You'll have to use the appropriate command line arguments as well. – L. Scott Johnson Apr 16 '20 at 14:33wc -l
– L. Scott Johnson Apr 16 '20 at 14:34