1

I am trying to figure out why with in my below code proc_count (RHEL 7.6 Bash) is not being set to 1 ? Its always set to 2. I am sure there is no other job running with the name temp. Also I am only seeing this incorrect result when I execute the command using $(). When the first command accurately print 1 as the output but proc_count is being set to 2.

I tested this 10 different times but could not crack where this is going wrong. Appreciate any inputs. May be I am missing something really simple.

BTW, this exact code produces output of 1 for $proc_count on AIX (7.2 Bash).

PS: The last grep is really not needed, I add it trying to figure this thing out.

cat temp.sh

    ```#!/bin/sh

    jobname=$(basename $0 .sh)
    echo $jobname

    ps -ef|grep -v grep|grep -v tail|grep "${jobname}"|grep -v grep|wc -l

    proc_count=$(ps -ef|grep -v grep|grep -v tail|grep "${jobname}"|grep -v grep|wc -l)
    echo $proc_count```

$ ./temp.sh

temp

1

2

Thanks! Raghu

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Raghu
  • 43
  • 1
  • 7
  • 1
    In general, counting process table entries is a bad idea in the first place. If you want to prevent duplicate instances of the same job from running, that's what advisory locking is for -- `flock` and similar tools. And if you *still* want to do it for some reason, use a tool that's built to handle the corner cases correctly out-of-the-box, like `pgrep`. – Charles Duffy Feb 14 '20 at 23:10
  • 2
    Anyhow -- what you're seeing is *the process itself*. Remember, a command substitution and a pipeline both run in a fork()-ed off copy of the current process, which thus gets its own process-table entry. You can grep out the `grep` from the pipeline, but you can't grep out the forked copy, *because it's identical to its parent*. – Charles Duffy Feb 14 '20 at 23:11

0 Answers0