211

I have a script in Bash called Script.sh that needs to know its own PID. In other words, I need to get PID inside Script.sh.

Any idea how to do this?

NotTheDr01ds
  • 15,620
  • 5
  • 44
  • 70
Debugger
  • 9,130
  • 17
  • 45
  • 53

7 Answers7

310

The variable $$ contains the PID.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Paul Tomblin
  • 179,021
  • 58
  • 319
  • 408
98

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).
YSC
  • 38,212
  • 9
  • 96
  • 149
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
46

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
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
10

The PID is stored in $$.

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

n.st
  • 946
  • 12
  • 27
neo
  • 1,260
  • 11
  • 22
  • `kill -9` (with `-9` flag) is considered to be harmful and only to be used if it is absolutely necessary). – Willem Van Onsem Sep 15 '15 at 15:01
  • 4
    It's considered "dangerous" because the process does not get a chance to respond to the signal (and possibly clean up after itself). Doing `kill -9 $$` does exactly 1 thing. It kills the **current shell process**. This is useful if you have done something in the shell session that you do not want written to `.bash_history` Like: `docker run -e PASSWORD=hunter2 ircbot` – Bruno Bronosky Oct 19 '17 at 04:05
8

You can use the $$ variable.

Klaus Byskov Pedersen
  • 117,245
  • 29
  • 183
  • 222
2

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

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.

Pierre13fr
  • 181
  • 2
  • 3