LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Find parent PID in shell script ? (https://www.linuxquestions.org/questions/programming-9/find-parent-pid-in-shell-script-526384/)

bugmenot 02-07-2007 08:54 AM

Find parent PID in shell script ?
 
Hello,

I know that I can with $$ inside shell script find out the PID of that shell script.

But how can I get parent PID of the same script inside shell script.

Example:

I have MyScript and MyScript1.
MyScript is calling MyScript1.
So if I inside MyScript1 write $$ I will get PID of MyScript1, but how to get PID of MyScript inside MyScropt1.

Is there a way?

Thanks

anomie 02-07-2007 09:06 AM

You can get Parent PID (PPID) using ps. These are the columns available with the -ef options:

Code:

[hector@troy ~]$ ps -ef | head -1
UID        PID  PPID  C STIME TTY          TIME CMD

Once you have your own PID, you can match it with awk and then print the 3rd column.
e.g.
Code:

ps -ef | awk '$2 ~ /\<1148\>/ { print $3; }'
where 1148 is your PID, and the result printed is its PPID.

druuna 02-07-2007 09:19 AM

Hi,

I assume you are using bash: You can use PPID.

Code:

$ cat ms
#!/bin/bash

echo "ms => $$"

./ms1

$ cat ms1
#!/bin/bash

echo "-- ms1 => $$"
echo "-- ms => $PPID"


$ ./ms
ms => 24158
-- ms1 => 24159
-- ms => 24158

Hope this helps.

anomie 02-07-2007 09:29 AM

Even easier -- I didn't know there was a special shell variable for PPID.

druuna 02-07-2007 09:32 AM

Hi,

Yep, it's a read-only variable set by bash. See the manpage (part about shell variables) for all the gory details ;)

bugmenot 02-07-2007 09:48 AM

Ok, good it is working also in "ksh"

schneidz 02-07-2007 11:53 AM

hi, what is the difference between $$ and $! ?

thanks,

druuna 02-07-2007 12:09 PM

Hi,

$$ -> Expands to the process ID of the (current) shell.
$! -> Expands to the process ID of the most recently executed background command.

man bash could have told you this......


All times are GMT -5. The time now is 11:28 PM.