I am trying to understand the "oneliner" in this comment by @sysfault:
/bin/sh -c 'echo $$>/tmp/my.pid && exec program args' &
I tried the following variations...
Different $$ inside and out:
/bin/bash -c 'echo $$ && exec sleep 5' ; echo $$
14408
29700
Same pid (but in background):
$ /bin/bash -c 'echo $$ && exec sleep 5' & echo $!
[1] 8309
8309
$ 8309
[ 1 ]+ Done /bin/bash -c 'echo $$ && exec sleep 5'
Different pid for $$ & $! :
/bin/bash -c 'echo $$ && exec sleep 5 & echo $!'
6504
6503
Kill did not work:
/bin/bash -c 'echo $$ && (sleep 15 ; echo done)'
19063
Killed
$ done (echo showed up after the kill)
Same pid with access to the pid of the foreground process:
$ /bin/bash -c 'echo > tmp.pid ; sleep 10 ; echo $$ ; echo done ; echo $$;'
28415 (instantly)
28415 (10 seconds later)
done
28415
$ cat tmp.pid
28415
With this command I was able to kill the pid in another window before the sleep finished - preventing the last three echos from happening:
$ /bin/bash -c 'echo $$ ; sleep 30 ; echo $$ ; echo done ; echo $$;'
23236
Killed
Context: Ultimately I want to start bash processes via php exec(), and wait for the result before continuing and save the pid so i can clean up in case the manual cancel button is pressed. There are 2 expensive processes i will deal with: one rsync and one git commit & push.
What is the best way to reliably get the pid of a foreground bash script that includes multiple commands (with ; > | or &&) ?