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

☆樱花仙子☆ 提交于 2019-12-31 07:58:09

问题


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 )

Any idea how to do this ?


回答1:


The variable '$$' contains the PID.




回答2:


use $BASHPID or $$

See the manual for more information, including differences between the two.

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.
  • $BASHPID Expands to the process ID of the current Bash process.
    • In a () subshell, it expands to the process ID of the subshell



回答3:


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

$ 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



回答4:


The PID is stored in $$.

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




回答5:


You can use the $$ variable.




回答6:


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:

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


来源:https://stackoverflow.com/questions/2493642/how-does-a-linux-unix-bash-script-know-its-own-pid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!