Search code examples
linuxbashpid

Get the pid of a command whose output is piped


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 &

Solution

  • 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.