Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

The explicit suggestion, based on Daniel Pittman's answer is:

bash -c 'echo $$ > /var/log/script.pid && exec /usr/bin/script -f sometext.log'
share|improve this question
    
Be careful: there is an actual UNIX/Linux command script; if that is the actual name, you should choose another. –  Mei Feb 21 '12 at 22:41
    
@David, note what I said at the bottom of the question, I'm getting the pid for the UNIX script command you just mentioned –  Mike Pennington Feb 21 '12 at 22:43

1 Answer 1

up vote 3 down vote accepted

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.

share|improve this answer
    
Thank you, but I'm still having a problem... I can't figure out how to make the exec option send the -f sometext.log option to script –  Mike Pennington Feb 21 '12 at 22:46
    
If you put exec in front of a regular bash command line it will replace itself with that command, rather than run the command and wait for it to exit. So, echo $$ > /var/lib/script.pid && exec /usr/bin/script -f sometext.log should do exactly what you want. –  Daniel Pittman Feb 21 '12 at 22:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.