0

I've a scirpt name server.sh

 #!/bin/bash

process_count=$(ps aux | grep server.sh | grep -v grep | wc -l ) echo "total process running:" echo $process_count

... other script code

when I run script I get output as

./server.sh
total process running:
2

Why do I get process count as 2 instead of 1? I only have one script running and have also excluded grep process. Even using pgrep -f server.sh and excluding pgrep gives 2 as process count.

1 Answers1

0
  1. if ps | grep | grep -v grep or pgrep are showing two processes then you have two matching processes running. See for yourself by running the ps ... pipeline without piping into wc -l.

  2. That's not pgrep, pgrep is a completely separate program from ps. See man pgrep for details but, in short, run pgrep -f server.sh | wc -l

  3. That's ps piped into grep, then grep -v, then wc -l. This matches one of its own pipeline processes (the first grep) because grep is searching for "server.sh" which happens to be the command line argument for grep server.sh.

  4. The usual method to avoid this (from the days before pgrep existed) is/was to grep for something that won't match its own command line, e.g. grep [s]erver.sh or grep server\\.sh, or just use awk:

    ps aux | awk '/[s]erver\.sh/ {count++}; END {print count}'
    

    or if you want to get the list of matching PIDs instead of the count:

    ps aux | awk '/[s]erver\.sh/ {print $1}'
    
  5. Also, the ps in the Linux procps package has long supported a -C cmdlist option to do an exact match on the basename portion of process executable names.

    e.g. ps -C apache2 will list apache2 processes even though ps aux | grep [a]pache2 shows that the full process names are actually /usr/sbin/apache2. This is not a regex match, it's an exact match on the basename - ps -C apache would not show apache2 processes.

    From man ps:

   -C cmdlist

Select by command name. This selects the processes whose executable name is given in cmdlist.

NOTE: The command name is not the same as the command line. Previous versions of procps and the kernel truncated this command name to 15 characters. This limitation is no longer present in both. If you depended on matching only 15 characters, you may no longer get a match.

cas
  • 78,579