在脚本中的$$ vs子shell中的$$

Ank*_*wal 11 bash shell scripting

$$ 在脚本中使用时给出脚本进程的进程ID,如下所示:

例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
Run Code Online (Sandbox Code Playgroud)

观察PID给出$$并且ps15326

我的shell提示符是pid 15073

但在子shell中,$$给出父shell的pid(15073)

例2

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

这里的子shell是pid 15340

问题:为什么会这样?脚本是否也在子shell中运行?示例2中的子shell与示例1中脚本运行的shell之间有什么区别?

flo*_*olo 14

我尝试并转义(将$$传递给子shell)不起作用,因为子shell从父bash继承$$值.解决方法是使用$ BASHPID.

(echo $$; echo $BASHPID)
Run Code Online (Sandbox Code Playgroud)

从父shell和子shell中打印PID.


Ton*_*roy 9

从bash手册页:

   $      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.
Run Code Online (Sandbox Code Playgroud)


Ign*_*ams 6

替换发生在父shell中; 替换发生时尚未启动子shell.

  • 是的,这不是关于谁替换; $$*在子shell中被评估,它只是有意地评估主shell的PID,如联机帮助页所示. (6认同)