Getting started with Linux: how to obtain the process ID (PID) in a script)

Source: Internet
Author: User

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:

  1. #! /Bin/bash
  2.  
  3. Echo "PID of this script: $"

The above script will get the following output:

  1. 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:

  1. #! /Bin/bash
  2.  
  3. Echo "PID of this script: $"
  4. Echo "PPID of this script: $ PPID"
  5. Echo "UID of this script: $ UID"

The output is:

  1. PID of this script: 6686
  2. PPID of this script: 4656
  3. 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.

  1. $ Man bash

This article permanently updates the link address:

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.