$$
gives process id of the script process when used in a script, like this:
Example 1
#!/bin/bash
# processid.sh
# print process ids
ps
I tried and escaping (to pass the $$ to the subshell) does not work as the subshell inherits the $$ value from the parent bash. The solution to this is to use $BASHPID.
(echo $$; echo $BASHPID)
prints the PID from the parent shell and from the subshell.
The replacement takes place in the parent shell; the subshell hasn't been started by the time the substitution takes place.
A more portable way, linux-only, but also compatible with dash:
read -r my_pid _ < /proc/self/stat
echo $my_pid
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.