bash 脚本中的 $$ 与子外壳中的 $$

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5615570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:46:24  来源:igfitidea点击:

$$ in a script vs $$ in a subshell

bashshellscripting

提问by Ankur Agarwal

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

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

Example 1

示例 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 psis 15326

观察由$$和给出的 pidps15326

My shell prompt is pid 15073

我的 shell 提示是 pid 15073

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

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

Example 2

示例 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

这里的子shell是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?

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

回答by flolo

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.

我尝试转义(将 $$ 传递给子外壳)不起作用,因为子外壳从父 bash 继承了 $$ 值。解决方案是使用 $BASHPID。

(echo $$; echo $BASHPID)

prints the PID from the parent shell and from the subshell.

从父 shell 和子 shell 打印 PID。

回答by Tony Delroy

From the bash manpage:

从 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.

回答by Ignacio Vazquez-Abrams

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

替换发生在父 shell 中;替换发生时子外壳尚未启动。

回答by drizzt

A more portable way, linux-only, but also compatible with dash:

一种更便携的方式,仅限 linux,但也与 dash 兼容:

read -r my_pid _ < /proc/self/stat
echo $my_pid