Output of echo $$ differs in Script than console

Hi All,

I have a very basic query for 'echo $$' command.

When I am executing echo $$ on console then it is giving different output than the execution of echo $$ in a script.

Console Output:
-------------------------
bash-3.2$ echo $$
15610
bash-3.2$

In Script:
--------------------
bash-3.2$ cat pid.sh
echo $$
bash-3.2$

bash-3.2$ ./pid.sh
13818
bash-3.2$ ./pid.sh
13820
bash-3.2$ ./pid.sh
13823
bash-3.2$

Also why is the output changing in script everytime whereas in case of running command direct from console it is not changing everytime.

Many thanks in advance.

Thank you-Manish Kumar

Well, from the name 'pid.sh' I hope you know what is $$ for. But executing a shell script your shell invokes another, child shell. And this shell is just another process. And if your start another terminal you get a different $$. Or if you just execute sh (or bash, or ksh) you get a different $$ too because all these shell would be different processes.
If you have troubles with understanding "pid" you can read more here - Process identifier - Wikipedia, the free encyclopedia.

From that wikipedia link:

That $$ statement is incorrect, though a common misconception. In a subshell the value of $$ is not the pid of the subshell, but that of an ancestor. $$ only actually reflect's the process pid when in an invoked shell's execution environment.

Take the following command:

echo $$ $(echo $$; sh -c 'echo $$')

The first $$ will match the invoked, top-level shell's pid. The second $$ is executed in a subshell whose pid is not $$, since $$ is still that of the parent, top-level (invoked) shell. The third $$ differs from the first two since it is printed from an invoked shell which sets $$ to its own pid.

If the top-level invoked shell has a pid of 10000, and the subshell created for the command subsitution is 10001, and the shell invoked from within the subshell (sh -c ...) is 10002, the output from this command would be "10000 10000 10002".

pid 10000 --> $$ 10000 (invoked shell)
pid 10001 --> $$ 10000 (subshell, pid-$$ mismatch)
pid 10002 --> $$ 10002 (invoked shell)

Personally, I don't conceive of $$ as being as much about current pid as about the current, invoked shell whose execution environment is currently in charge and propagating to subshells.

In actuality, $$ could be a pid, a parent pid (subshell), a grandparent's pid (subshell within a subshell) ...

Regards,
Alister

Yes, in an "inner" subshell ( in "(...)" or "$(...)" or "`...`") you get the same $$. But I'm afraid this only confuses the topic starter. You shouldn't learn to the letter "Z" not knowing "A", is not it? :slight_smile: