user13215247
user13215247

Reputation:

Get Number Of Running Processes By Name In Bash

Suppose I run the following in terminal:

pgrep Google Chrome

and it produces the following output of all the PID's:

110
311
142

How could I display exactly how many processes have been listed without counting myself to produce something like:

110
311
142

There are currently 3 processes running under the application 'Google Chrome'

Upvotes: 0

Views: 281

Answers (3)

Mansou4
Mansou4

Reputation: 11

You can use this command :

pgrep -c <process name>

Example :

pgrep -c chromium

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 246827

I find wrapper functions quite helpful for this kind of thing:

pgrep() {
  local app=${!#} pids
  # now invoke the *command* pgrep and
  # capture the output into an array of lines
  readarray -t pids < <(command pgrep "$@")
  # print the output
  printf "%s\n" "${pids[@]}"
  # and print the summary
  printf "\nThere are currently %d processes running under the application '%s'\n" \
    "${#pids[@]}" \
    "$app"
}

This also lets you use pgrep options, like pgrep -fl "Google Chrome"

The problem is that pgrep allows you to specify multiple patterns, and this function only captures the last one as "the application."

Upvotes: 1

M. Nejat Aydin
M. Nejat Aydin

Reputation: 10123

In order to produce the output in the format you specified:

proc="Google Chrome"

pids=$(pgrep "$proc")
if [[ -n $pids ]]; then
    printf "%s\n\nThere are currently %d processes running under the application '%s'\n" \
        "$pids" "$(wc -l <<< "$pids")" "$proc"
fi

Upvotes: 0

Related Questions