3

In order to remotely start a program, log its output and immediately see that log, I'm using this script:

nohup mycommand 2>&1 | tee -a server.log &

Now, I would like to store in a file the pid of the newly started mycommand (whose name is very generic, I can't just use pgrep as there would be a risk of collision).

If I just add echo $! > mycommand.pid I get the pid of tee.

How can I reliably write the pid of mycommand to a file ?

And by the way, why doesn't this give the right pid ?

( nohup mycommand 2>&1 ; echo $! > mycommand.pid ) | tee -a server.log &
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Possible duplicate: http://stackoverflow.com/questions/3345460/how-to-get-the-pid-of-a-process-in-a-pipeline – anubhava Nov 05 '14 at 10:18

1 Answers1

1

OK, this simple variant works :

( nohup mycommand 2>&1 & echo $! > mycommand.pid ) | tee -a server.log &

I'm not sure why the ; didn't work and why I have to use & instead.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • I just accepted my answer because it's been 3 months. But if somebody writes a better answer with a solid explanation, I'll be glad to accept it. – Denys Séguret Feb 10 '15 at 16:17
  • I think the ; didn't work because it means wait for the first command to finish - at which point the pid is gone? – artfulrobot May 26 '23 at 11:27