Following the answer by @Gilles which I encountered whilst solving another problem that I had, I threw together a quick test program that underpins the theory that the correct answer is:
MYPID=$(exec sh -c 'echo $PPID')
I found there are times when exec
isn't required but I confirmed that using it is the only way to get the correct pid all of the time in all of the shells I tried. Here is my test:
#!/bin/sh
pids() {
echo ------
pstree -pg $PPID
echo 'PPID = ' $PPID
echo '$$ = ' $$
echo 'BASHPID =' $BASHPID
echo -n 'sh -c echo $PPID = '; sh -c 'echo $PPID'
echo -n '$(sh -c '\''echo $PPID'\'') = '; echo $(sh -c 'echo $PPID')
echo -n '$(exec sh -c '\''echo $PPID'\'') = '; echo $(exec sh -c 'echo $PPID')
echo -n 'p=$(sh -c '\''echo $PPID'\'') = '; p=$(sh -c 'echo $PPID') ; echo $p
echo -n 'p=$(exec sh -c '\''echo $PPID'\'') = '; p=$(exec sh -c 'echo $PPID') ; echo $p
}
pids
pids | cat
echo -e "$(pids)"
and its output
------
bash(5975,5975)---pidtest(13474,13474)---pstree(13475,13474)
PPID = 5975
$$ = 13474
BASHPID = 13474
sh -c echo $PPID = 13474
$(sh -c 'echo $PPID') = 13474
$(exec sh -c 'echo $PPID') = 13474
p=$(sh -c 'echo $PPID') = 13474
p=$(exec sh -c 'echo $PPID') = 13474
------
bash(5975,5975)---pidtest(13474,13474)-+-cat(13482,13474)
`-pidtest(13481,13474)---pstree(13483,13474)
PPID = 5975
$$ = 13474
BASHPID = 13481
sh -c echo $PPID = 13481
$(sh -c 'echo $PPID') = 13481
$(exec sh -c 'echo $PPID') = 13481
p=$(sh -c 'echo $PPID') = 13481
p=$(exec sh -c 'echo $PPID') = 13481
------
bash(5975,5975)---pidtest(13474,13474)---pidtest(13489,13474)---pstree(13490,13474)
PPID = 5975
$$ = 13474
BASHPID = 13489
sh -c echo $PPID = 13489
$(sh -c 'echo $PPID') = 13492
$(exec sh -c 'echo $PPID') = 13489
p=$(sh -c 'echo $PPID') = 13495
p=$(exec sh -c 'echo $PPID') = 13489
Substitute your favourite shell in the shebang: sh
, bash
, mksh
, ksh
, etc...
I don't understand why cases 2 and 3 give different results, nor why the results for case 3 differ between shells. I tried bash
, ksh
and mksh
on Arch Linux FWIW.
$(exec sh -c 'echo $PPID')
However the initial simple commandsh -c 'echo $PPID'
gives a third PID. So thanks for the solution. Accepted. – Patkos Csaba Feb 27 '12 at 08:29$BASHPID
be emulated withsh -c 'echo $PPID'
? I tried(sh -c 'echo $PPID')
and(exec sh -c 'echo $PPID')
in Bash but both give me the same PID as$$
. – Franklin Yu Aug 22 '18 at 17:26(sh -c 'echo $PPID')
to avoid creating a subshell. Contrast with(sh -c 'echo $PPID'; true)
. This optimization only kicks in if you try to access$BASHPID
as the very last thing before the subshell exits, i.e. only in cases where you can't do anything with the value. So in practice, you can replace$BASHPID
with$(sh -c 'echo $PPID')
. – Gilles 'SO- stop being evil' Aug 22 '18 at 17:32$BASHPID
in Zsh? – Franklin Yu Aug 22 '18 at 18:19sh -c 'echo $PPID'
. – Gilles 'SO- stop being evil' Aug 22 '18 at 18:41