Search code examples
linuxcommand-lineprocesscount

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.


Solution

  • On Linux systems (and perhaps some non-Linux systems as well) that have pgrep available, the -c/--count option returns a count of the number of processes that match the given name:

    pgrep --count command_name
    

    If pgrep is not available, you may be able to use ps and wc. Again this may be somewhat system-dependent, but on typical Linux systems the following command will get you a count of processes:

    ps -C command_name -e --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. -e causes it to search processes owned by all users, not just the calling user. 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.

    There are a few key differences between these commands:

    • pgrep uses grep-style matching, so e.g. pgrep sh will also match bash processes. If you want an exact match, also use the -x/--exact option. On the other hand, ps -C uses exact matching, not grep-style.
    • ps will output a row for itself and/or any other process it's being piped to, if those match the process selection criteria you gave. So ps -C ps --no-headers | wc -l and ps -C wc --no-headers | wc -l will always output at least 1, because they are counting themselves. On the other hand, pgrep excludes itself. So pgrep --count pgrep will output 0 unless there are other separate pgrep processes running. (Typically the pgrep behavior is what you want, which is why I generally recommend using pgrep if it's available.)

    Here's a summary of a few variations:

    Use case pgrep ps
    Exact match pgrep -x -c command_name ps -C command_name -e --no-headers | wc -l
    Substring match pgrep -c command_name N/A
    Only current user pgrep -U "$UID" -c command_name ps -C command_name --no-headers | wc -l

    There are many more possibilities, too many to list here. Check the man pages for pgrep and ps if you need different behavior, and you might find an option that implements it.