Linux/Unix Bash 脚本如何知道自己的 PID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2493642/
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-09 19:05:24  来源:igfitidea点击:

How does a Linux/Unix Bash script know its own PID?

bashscriptingpid

提问by Debugger

I have a script in Bash called Script.sh, and it needs to know its own PID (i.e. I need to get PID inside the Script.sh )

我在 Bash 中有一个名为 的脚本Script.sh,它需要知道自己的 PID(即我需要在 Script.sh 中获取 PID)

Any idea how to do this ?

知道如何做到这一点吗?

回答by Paul Tomblin

The variable '$$' contains the PID.

变量“$$”包含PID。

回答by tvanfosson

use $BASHPIDor $$

使用$BASHPID$$

See the manualfor more information, including differences between the two.

有关更多信息,包括两者之间的差异,请参阅手册

TL;DRTFM

TL;DRTFM

  • $$Expands to the process ID of the shell.
    • In a ()subshell, it expands to the process ID of the invoking shell, not the subshell.
  • $BASHPIDExpands to the process ID of the current Bash process.
    • In a ()subshell, it expands to the process ID of the subshell
  • $$扩展到 shell 的进程 ID。
    • ()子shell 中,它扩展为调用shell 的进程ID,而不是子shell。
  • $BASHPID扩展为当前 Bash 进程的进程 ID。
    • ()子shell中,它扩展为子shell的进程ID

回答by Paused until further notice.

In addition to the example given in the Advanced Bash Scripting Guidereferenced by Jefromi, these examples show how pipes create subshells:

除了Jefromi引用的Advanced Bash Scripting Guide 中给出的示例之外,这些示例展示了管道如何创建子外壳:

$ echo $$ $BASHPID | cat -
11656 31528
$ echo $$ $BASHPID
11656 11656
$ echo $$ | while read line; do echo $line $$ $BASHPID; done
11656 11656 31497
$ while read line; do echo $line $$ $BASHPID; done <<< $$
11656 11656 11656

回答by neo

The PID is stored in $$.

PID 存储在$$.

Example: kill -9 $$will kill the shell instance it is called from.

示例:kill -9 $$将终止调用它的 shell 实例。

回答by Klaus Byskov Pedersen

You can use the $$variable.

您可以使用该$$变量。

回答by Joakim J. Rapp

If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

如果进程是子进程并且没有设置$BASHPID,则可以查询正在运行的进程创建的子进程的ppid。它可能有点难看,但它有效。例子:

sleep 1 &
mypid=$(ps -o ppid= -p "$!")