$BASHPID 和 $$ 在某些情况下不同

Per*_*ulf 10 shell bash process parameter subshell

我正在阅读“Oreilly 的 BASH 袖珍指南”。它说:

当前 Bash 进程的进程 ID。在某些情况下,这可能与 $$ 不同。

以上解释,解释$BASHPID变量。

问题:哪些情况?

jor*_*anm 21

BASHPIDbash 联机帮助页的描述中提供了一个示例:

   BASHPID
          Expands to the process id of the  current  bash  process.   This
          differs  from  $$ under certain circumstances, such as subshells
          that do not require bash to be re-initialized.
Run Code Online (Sandbox Code Playgroud)

这是一个子shell的示例,它输出变量$$的内容以及BASHPID子shell外部的内容。

$ echo $(echo $BASHPID $$)      $$       $BASHPID
              25680    16920    16920    16920
#             |        |        |        |
#             |        |        |        -- $BASHPID outside of the subshell
#             |        |        -- $$ outside of the subshell
#             |        -- $$ inside of the subshell
#             -- $BASHPID inside of the subshell
Run Code Online (Sandbox Code Playgroud)


orm*_*aaj 15

子壳。$$由 POSIX 指定并始终保持原始 shell 进程的值。$BASHPID是 Bash 特定的变量,并且始终是取消引用该变量的进程的值,计算子 shell。

 $ f() { printf '%s: %d, %d\n' "$1" $$ $BASHPID; };
 $ ${BASH_VERSION+shopt -s lastpipe}; set +m;
 $ f 1 >&2 | f 2
2: 31490, 31490
1: 31490, 32545
Run Code Online (Sandbox Code Playgroud)

我确实设法说服 mksh 维护者添加BASHPID到最新版本,所以它有点便携。也可以BASHPID自己在ksh93中在很多平台上实现。

  • @TheQuark只有bash有`shopt`,并且只有bash(和ksh93v-)具有可配置的“lastpipe”行为,尽管它们的默认值是向后的。`${var+}` 也不是一个特别好的机制,因为它是字段分割的。当在不由其他脚本获取的脚本顶部使用时,它对于具有已知“IFS”的字符串文字可以正常工作。 (2认同)