0

Given a process pid, how can I

  • check if the process is running a shell script?

  • if yes, how can I get the child process(es) which the script is running? by pgrep -P <pid>?

Thanks.

3

1 Answer 1

0

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.

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:

$ cat xyz.sh
#!/bin/bash
echo "PID of this script: $$"

Which gives the following output

PID of this script: XXXX

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. Like this(only example)

#!/bin/bash
echo "PID of this script: $$"
echo "PPID of this script: $PPID"
echo "UID of this script: $

Which gives the output

PID of this script: XXXX 
PPID of this script: XXXX 
UID of this script: XXXX
1
  • This is not answering the question posed, as the questioner pointed out in question comments. This is starting from having a shell script and finding its process ID. The question posed is starting from having a process ID and finding a shell script, if any. Note the first four words of the body of the question.
    – JdeBP
    Jul 28, 2018 at 10:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .