Feb 21, 2012
tom

PID of a command executed in bash

Question

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.

Answer

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.

Answered by Daniel Pittman

Related posts:

  1. Bash child proccess PID – how do you get it?
  2. Check pid of GeoServer running with Jetty
  3. bash shell command runs fine at command prompt, but not in my .sh script?
  4. ~bash: command not found to any command after server restart!
  5. How to get pid of just started process

Leave a comment