Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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/

Such that the PID of script -f sometext.log is written to /var/log/

script is the the command I'm executing.

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

bash -c 'echo $$ > /var/log/ && 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
up vote 3 down vote accepted

You can do what you want with this code:

echo $$ > /var/log/ && 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/ && exec /usr/bin/script -f sometext.log should do exactly what you want. – Daniel Pittman Feb 21 '12 at 22:49

Your Answer


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.