I was looking for the best way to find the number of running processes with the same name via the command line in Linux. For example if I wanted to find the number of bash processes running and get "5". Currently I have a script that does a 'pidof ' and then does a count on the tokenized string. This works fine but I was wondering if there was a better way that can be done entirely via the command line. Thanks in advance for your help.
You can list running processes using the ps command (ps means process status). The ps command displays your currently running processes in real-time. This will display the process for the current shell with four columns: PID returns the unique process ID.
To list currently running processes, use the ps , top , htophtopAugust 2022) htop is an interactive system-monitor process-viewer and process-manager. It is designed as an alternative to the Unix program top.https://en.wikipedia.org › wiki › Htophtop - Wikipedia , and atop Linux commands. You can also combine the ps command with the pgrep command to identify individual processes.
wc stands for word count. As the name implies, it is mainly used for counting purpose. It is used to find out number of lines, word count, byte and characters count in the files specified in the file arguments.
The ps -p <PID> command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.
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.
result=`ps -Al | grep command-name | wc -l` echo $result
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With