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

BashScriptingPid

Bash Problem Overview


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 ?

Bash Solutions


Solution 1 - Bash

The variable $$ contains the PID.

Solution 2 - Bash

use $BASHPID or $$

See the [manual][1] 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 (new to bash 4).

Solution 3 - Bash

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

Solution 4 - Bash

The PID is stored in $$.

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

Solution 5 - Bash

You can use the $$ variable.

Solution 6 - Bash

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 "$!")

Solution 7 - Bash

Wherever you are (on an interactive command line or in a script), and in the case you do NOT have access to $BASHPID, you can get access to your current shell pid with this :

bash -c 'echo $PPID'

where simple quotes are essential to prevent premature string interpretation (so as to be sure the interpretation occurs in the child process, not in the current one). The principle is just to create a child process and ask for its parent pid, that is to say "myself". This code is simpler than ps-based Joakim solution.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDebuggerView Question on Stackoverflow
Solution 1 - BashPaul TomblinView Answer on Stackoverflow
Solution 2 - BashtvanfossonView Answer on Stackoverflow
Solution 3 - BashDennis WilliamsonView Answer on Stackoverflow
Solution 4 - BashneoView Answer on Stackoverflow
Solution 5 - BashKlaus Byskov PedersenView Answer on Stackoverflow
Solution 6 - BashJoakim J. RappView Answer on Stackoverflow
Solution 7 - BashPierre13frView Answer on Stackoverflow