Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$$ in a script vs $$ in a subshell

$$ gives process id of the script process when used in a script, like this:

Example 1

#!/bin/bash
# processid.sh
# print process ids

ps -o cmd,pid,ppid
echo "The value of \$\$ is $$"

$ ./processid.sh 
CMD                           PID  PPID
bash                        15073  4657
/bin/bash ./processid.sh    15326 15073
ps -o cmd,pid,ppid          15327 15326
The value of $$ is 15326

Observe the pid given by $$ and ps is 15326

My shell prompt is pid 15073

But in a subshell, $$ gives pid of parent shell (which is 15073)

Example 2

$ ( ps -o cmd,pid,ppid ; echo $$ )
CMD                           PID  PPID
bash                        15073  4657
bash                        15340 15073
ps -o cmd,pid,ppid          15341 15340
15073

Here subshell is pid 15340

Question: Why so? Isn't the script also running in a subshell? What's the difference between the subshell in example 2 and the shell in which the script runs in example 1?

like image 540
Ankur Agarwal Avatar asked Apr 11 '11 00:04

Ankur Agarwal


People also ask

What does $$ mean in shell script?

$$ is the pid (process id) of the shell interpreter running your script. It's different for each process running on a system at the moment, but over time the pid wraps around, and after you exit there will be another process with same pid eventually.As long as you're running, the pid is unique to you.

What is $1 $2 in shell script?

$1, $2, $3 etc. represent the first, second, third, etc. arguments to the script. $# represents the number of arguments. $* represents the string of arguments.

What is a subshell in shell script?

Definition: A subshell is a child process launched by a shell (or shell script). A subshell is a separate instance of the command processor -- the shell that gives you the prompt at the console or in an xterm window.

What is the difference between $$ and in Unix?

The $@ holds list of all arguments passed to the script. The $* holds list of all arguments passed to the script.


2 Answers

From the bash manpage:

   $      Expands  to  the  process ID of the shell.  In a () subshell, it
          expands to the process ID of the current  shell,  not  the  sub-
          shell.
like image 179
Tony Delroy Avatar answered Nov 16 '22 01:11

Tony Delroy


The replacement takes place in the parent shell; the subshell hasn't been started by the time the substitution takes place.

like image 36
Ignacio Vazquez-Abrams Avatar answered Nov 16 '22 00:11

Ignacio Vazquez-Abrams