Finding process count in Linux via command line
result=`ps -Al | grep command-name | wc -l`
echo $result
On systems that have pgrep
available, the -c
option returns a count of the number of processes that match the given name
pgrep -c command_name
Note that this is a grep
-style match, not an exact match, so e.g. pgrep sh
will also match bash
processes. If you want an exact match, also use the -x
option.
If pgrep
is not available, you can use ps
and wc
.
ps -C command_name --no-headers | wc -l
The -C
option to ps
takes command_name
as an argument, and the program prints a table of information about processes whose executable name matches the given command name. This is an exact match, not grep
-style. The --no-headers
option suppresses the headers of the table, which are normally printed as the first line. With --no-headers
, you get one line per process matched. Then wc -l
counts and prints the number of lines in its input.