Methods to get Process IDs in shell scripts _linux shell

Source: Internet
Author: User

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:

PID of this script:6583

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:

$ Man Bash

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.