Bash - Two processes for one script

I have a shell script called test.sh:

#!/bin/bash
echo "start"
ps xc | grep test.sh | grep -v grep | wc -l
vartest=`ps xc | grep test.sh | grep -v grep | wc -l `
echo $vartest
echo "end"

      

Output Result:

start
1
2
end

      

So my question is, why are there two test.sh processes when I call ps with `` (same thing happens with $ ()) and not when I call ps directly? How can I get the desired output (1)?

+3


source to share


1 answer


When you run a subshell, as with backticks, bash will impersonate itself, then execute the command you want to run. Then you also start a pipeline that calls all those that will run in their own subshells, so you end up with an "extra" copy of the script waiting for the pipeline to finish so that it can collect the output and revert that back to the original script.

We'll experiment a bit with using (...)

to explicitly start processes in subshells and using a command pgrep

that does it for us ps | grep "name" | grep -v grep

, just showing us the processes that match our string:

echo "Start"
(pgrep test.sh)
(pgrep test.sh) | wc -l
(pgrep test.sh | wc -l)
echo "end"

      



which, when run, produces the output for me:

Start
30885
1
2
end

      

So we can see that running pgrep test.sh

in a subshell only finds a single instance of test.sh, even if that subshell is part of the pipeline itself. However, if the subshell contains a pipeline, we end up with a forked copy of the script waiting for the pipeline to finish.

+6


source







All Articles