Question: I want to know the process ID of the script shell in the run. How do I get the PID in the shell script?
When I execute the shell script, it starts a process called a child shell. As a child of the main shell, the child shell runs the command in the shell script as a batch (hence, it is called a "batch process").
In some cases, you might want to know the PID of the sub shell in operation. This PID information can be used in different situations. For example, you can use the PID of the shell script to create a unique temporary file in/tmp. Sometimes a script needs to detect all running processes, and it can exclude its own child shell from the list of processes.
In bash, the PID of the child shell process is stored in a special variable ' $$ '. This variable is read-only and you cannot modify it in the script. Like what:
Copy Code code as follows:
#!/bin/bash
echo "PID of this script: $$"
The script above will get the following output:
Copy Code code as follows:
In addition to $$, the bash shell also exports other read-only variables. For example, PPID stores the ID of the child Shell parent process (that is, the main shell). The UID stores the current user ID that executes this script. Like what:
Copy Code code as follows:
#!/bin/bash
echo "PID of this script: $$"
echo "PPID of this script: $PPID"
echo "UID of this script: $UID"
The output is:
Copy Code code as follows:
PID of this script:6686
PPID of this script:4656
UID of this script:1000
In the output above, each execution of the PID will change. This is because a new shell will be created each time it runs. On the other hand, Ppid will always be the same as long as you are running in the same shell.
For all bash built-in variable lists, refer to the man page.
Copy Code code as follows: