Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding process count in Linux via command line

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.

like image 850
Traker Avatar asked Jun 17 '10 00:06

Traker


People also ask

How do I count the number of running processes on Linux?

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.

How can I get a list of all processes?

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.

What is the count command in Linux?

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.

How get PID details in Linux?

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.


2 Answers

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.

like image 89
David Z Avatar answered Sep 23 '22 19:09

David Z


result=`ps -Al | grep command-name | wc -l` echo $result 
like image 21
Amardeep AC9MF Avatar answered Sep 25 '22 19:09

Amardeep AC9MF