How could I write a Bash-script that runs a long running program and stores the programs process id in a separate file?

I want something like

exec long_running_tool
echo `ps af |grep "long_running_tool" |awk '$5 == "long_running_tool" {print $1}'` > pid_file

However doing exactly this would execute the ps after tool has finished.

Is there a way to get the process id of the process created?

  • 2
    Your sample code won't work because exec doesn't fork, so the shell process is replaced by the long_running_tool process. Consequently, exec never returns and the following line is never reached. See help exec, execve(2). Jan 27, 2011 at 10:04
  • @e-t172 thank you for pointing out. I delete 'exec' then.
    – DerMike
    Jan 27, 2011 at 10:24
  • 2
    Please see Process Management. Jan 27, 2011 at 10:44

2 Answers 2


You can easily run the process in the background with "&", then get the PID of the background process using "$!"

long_running_tool &
echo $! > pid_file

Then, optionally, wait $! if you want the shell to block until the process completes execution.

  • 1
    UPDATE: when I use the fg I get 'fg: 21: job (null) not created under job control' and the script does not block. Sorry.
    – DerMike
    Jan 27, 2011 at 10:23
  • "wait $!" should have a similar effect to fg that I can confirm does in fact, work in a script. I should probably have checked that before posting. >.> my bad. Jan 27, 2011 at 10:29
echo $$ > fooapp.pid
exec fooapp

As mentioned earlier, exec replaces bash with the specified program, retaining the PID.

  • interesting. this is useful esp. putting it in a sub-shell ( ... ). I wonder what's the pros/cons compared to backgrounding and wait.
    – Kay
    Sep 29, 2022 at 5:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .