0

I am trying to count process instances using the following command:

$ ps -ef | grep "test.sh" | egrep -v "grep|vi|more|pg" | wc -l
1

Which works perfectly on the command line, but in the script when I assign the output to a variable:

script_instances=`ps -ef | grep "test.sh" | egrep -v "grep|vi|more|pg" | wc -l`
echo $script_instances

Outputs:

2

It increments by 1, which I don't understand why it's happening.

If I just put following command in script it prints correctly

ps -ef | grep "test.sh" | egrep -v "grep"

Output:

root 14243 12162 0 19:12 pts/1 00:00:00 sh test.sh

I am on Ubuntu 14.04.5 LTS

roy
  • 6,344
  • 24
  • 92
  • 174
  • If you remove the `wc -l` and look at the contents of `script_instances`, what do you see? – Benjamin W. Jul 30 '18 at 19:05
  • @BenjaminW. Updated my Question – roy Jul 30 '18 at 19:15
  • Ideally, **don't use `ps | grep` at all**. The `pgrep` command will do the above, but also innately avoid matching itself. – Charles Duffy Jul 30 '18 at 19:46
  • (And if your goal is to ensure that there's only one instance of a script, the most reliable way to do that is with a lockfile; that way you don't have a problem if someone's opening a file in an editor you didn't know about and blacklist, or if there's another script by the same name, etc). – Charles Duffy Jul 30 '18 at 19:47

2 Answers2

0

Following fixed the issue grep -cw "test.sh"

script_instances=`ps -ef | grep -cw "test.sh" | egrep -v "grep|vi|more|pg" | wc -l`
roy
  • 6,344
  • 24
  • 92
  • 174
0

Don't use grep foo | grep -v grep, that gets processed by grep when the shell executes grep, instead use [ ] to get the pattern of your script name.

$ ps -ef | grep -c '[te]st.sh'

-c counts the number of matches
iamauser
  • 11,119
  • 5
  • 34
  • 52
  • 2
    Maybe you mean `[t]est.sh`? `[te]st.sh` only matches `tst.sh` or `est.sh` (plus any variants of the above with the `.` replaced with another character, since it's a wildcard in regex notation). – Charles Duffy Jul 30 '18 at 19:44
  • 2
    ...actually, `test[.]sh` would be a better place to be -- that way you stop the `.` from being treated as a wildcard, *and* prevent the process from matching itself. – Charles Duffy Jul 30 '18 at 19:46