Quantcast
Viewing latest article 2
Browse Latest Browse All 2

What is the difference between $$ and $! when using /bin/bash -c

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 $$1440829700

Same pid (but in background):

$ /bin/bash -c 'echo $$ && exec sleep 5'& echo $! [1] 83098309$ 8309[ 1 ]+  Done  /bin/bash -c 'echo $$ && exec sleep 5'

Different pid for $$ & $! :

/bin/bash -c 'echo $$ && exec sleep 5 & echo $!'65046503

Kill did not work:/bin/bash -c 'echo $$ && (sleep 15 ; echo done)'
19063Killed$ 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)done28415$ 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 $$;'23236Killed

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 &&) ?


Viewing latest article 2
Browse Latest Browse All 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>