PID of a command executed in bash
I need a linux / unix command that will execute another command and write the PID of the command it executes to a file… is there such a command?
I am not looking for any scheme that puts processes in the background and leverages the shell var $!
Example:
Assume the command I am looking for is execwritepid. I need to be able to call:
execwritepid -e "/usr/bin/script -f sometext.log" -f /var/log/script.pid
Such that the PID of script -f sometext.log is written to /var/log/script.pid
script is the the command I’m executing.
SOLUTION
The explicit solution, based on Daniel Pittman’s answer is:
bash -c 'echo $$ > /var/log/script.pid && exec /usr/bin/script -f sometext.log'
I could not get the option that uses exec to pass -f to script.
You can do what you want with this code:
echo $$ > /var/log/script.pid && exec /usr/bin/script
exec replaces the current process with another – which means that it retains the current pid.
If you want your parent script to carry on you can wrap that:
bash -c 'echo $$ && exec /usr/bin/script'
That will run the subcommand in a new shell, record the PID, then replace itself with the other process.
Check more discussion of this question.
Related posts:
Leave a comment
Recent Posts
- Windows File Permissions and Attributes
- What is the easiest way to upgrade my existing Perl 5.14 to Perl 5.16 on FreeBSD 9 using the ports system?
- Know if mysql has done its job
- Redirect https .com to https .co.uk without a valid SSL cert on .com without DNS change
- Why is it a bad idea to use customer email as from address





