How does a Linux/Unix Bash script know its own PID?
170,220
Solution 1
The variable $$
contains the PID.
Solution 2
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.
- In a
-
$BASHPID
Expands to the process ID of the current Bash process (new to bash 4).- In a
()
subshell, it expands to the process ID of the subshell [1]: http://www.gnu.org/software/bash/manual/bashref.html#Bash-Variables
- In a
Solution 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
Solution 4
The PID is stored in $$
.
Example: kill -9 $$
will kill the shell instance it is called from.
Solution 5
You can use the $$
variable.
Related videos on Youtube
Author by
Debugger
Updated on November 25, 2021Comments
-
Debugger over 2 years
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 ?
-
Sopalajo de Arrierez about 10 yearscould you please explain what does "<<<" mean? Thanks.
-
SourceSeeker about 10 yearsIt redirects a string into the loop (or anything that reads
stdin
). The string is referred to as a "here string". -
Willem Van Onsem over 8 years
kill -9
(with-9
flag) is considered to be harmful and only to be used if it is absolutely necessary). -
Bruno Bronosky over 6 yearsIt'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
-
Murtaza Haji about 2 yearsHow can i get the pid from outside the script , i use
top
but it shows a lot of random processes