I am trying to search for a shell script if it is running and then assigning the count to a variable. Let the script be ScriptXYZ.sh. I wrote:

proc_count=$(/bin/ps -ef | grep ScriptXYZ.sh | grep -v grep | wc -l)

The problem that I am facing is that even when there is no instance of the ScriptXYZ.sh running I get a proc_count = 2. I tried running the command directly in the terminal and it yielded zero. But this variable always fetches value 2. I tried to put the quotes around it.

proc_count="$(/bin/ps -ef | grep ScriptXYZ.sh | grep -v grep | wc -l)"

But that also didn't change the value. Can anyone please explain why is this happening?

Recommended Answers

All 3 Replies

Hello,

The first thing to do is to run the command and see what the output is. When I run the following on my system I get the 0 you are looking for:

[rod@hpsrvr ~]$ /bin/ps -ef | grep ScriptXYZ.sh | grep -v grep | wc -l
0

There is no reason that this should not work.
There must be something else in you program that it does not like.
I used your example but checked for httpd instead of a script and th ran fine.

[rod@hpsrvr ~]$ cat test.sh
#!/bin/bash
myvar=$( /bin/ps -ef | grep httpd | grep -v grep | wc -l)
echo $myvar
[rod@hpsrvr ~]$ ./test.sh
12

Post your code and maybe we will see something.

hi,

pgrep -c XYZ.sh

that's it! XD

Just to add some information that I am runnig it like:

>bash ScriptXYZ.sh [parameters]

and pgrep doesn't show the script as process.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.