Getting started with Linux: how to obtain the process ID (PID) in a script)
Question: I want to know the process id of the shell in the running script. How can I get the PID in the shell script.
When I execute a shell script, it starts a process called a sub-shell. As a sub-process of the main shell, the sub-shell runs the commands in the shell script as a batch (so it is called a "Batch Process ").
In some cases, you may want to know the PID of the sub-shell in the running state. This PID information can be used in different cases. For example, you can use the PID of the shell script to create a unique temporary file under/tmp. Sometimes the script needs to detect all running processes. It can exclude its own sub-shell from the process list.
In bash, the PID of the sub-shell process is stored in a special variable '$. This variable is read-only and cannot be modified in the script. For example:
- #! /Bin/bash
-
- Echo "PID of this script: $"
The above script will get the following output:
- PID of this script: 6583
In addition to $, bash shell exports Other Read-Only variables. For example, PPID stores the ID of the Child shell parent process (that is, the primary shell ). UID stores the current user ID that executes the script. For example:
- #! /Bin/bash
-
- Echo "PID of this script: $"
- Echo "PPID of this script: $ PPID"
- Echo "UID of this script: $ UID"
The output is:
- PID of this script: 6686
- PPID of this script: 4656
- UID of this script: 1000
In the above output, the PID changes every execution. This is because a new shell is created every time you run it. On the other hand, PPID will be the same every time as long as you run in the same shell.
For a list of all bash built-in variables, refer to the man page.
- $ Man bash
This article permanently updates the link address: