How to get the process ID (PID) of a shell script

Last updated on July 12, 2020 by Dan Nanni

Question: I want to know the process ID (PID) of the subshell under which my shell script is running. How can I find a PID in a bash shell script?

When you execute a shell script, it will launch a process known as a subshell. As a child process of the main shell, a subshell executes a list of commands in a shell script as a batch (so-called "batch processing").

In some cases, you may want to know the process ID (PID) of the subshell where your shell script is running. This PID information can be used under different circumstances. For example, you can create a unique temporary file in /tmp by naming it with the shell script PID. In case a script needs to examine all running processes, it can exclude its own subshell from the process list.

In bash, the PID of a shell script's subshell process is stored in a special variable called $$. This variable is read-only, and you cannot modify it in a shell script. For example:


echo "PID of this script: $$"

The above script will show the following output.

PID of this script: 6583

Besides $$, bash shell exports several other read-only variables. For example, PPID stores the process ID of the subshell's parent process (i.e., main shell). UID stores the user ID of the current user who is executing the script. For example:


echo "PID of this script: $$"
echo "PPID of this script: $PPID"
echo "UID of this script: $UID"

Its output will be:

PID of this script: 6686
PPID of this script: 4656
UID of this script: 1000

In the above, PID will keep changing every time you invoke a script. That is because each invocation of a script will create a new subshell. On the other hand, PPID will remain the same as long as you run a script inside the same shell.

For a complete list of built-in bash variables, refer to its man page.

$ man bash

If you find this tutorial helpful, I recommend you check out the series of bash shell scripting tutorials provided by Xmodulo.

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean