0

I want to save the PID of a nohup process as part of the name of nohup's generated output file.

This is going in the right direction, but only works if the process with it's ID is already settled, i.e. only works at the next line. That means that it does not work, because it's the wrong PID (from the last command):

nohup echo "hello World" > nohup_out_`echo $!`.txt &

Is there any way to save the resulting PID in nohup's output filename?

2 Answers 2

2

Note: `echo $!` gets you a "useless use of echo" award.

You can create the file yourself and rename it after nohup has opened it. You have to make sure that the file stays on the same filesystem so that the inode does not change. If the inode does not change, you can rename it, while nohup writes to the file. The command mv will not move anything in this case. Instead it will just modify the directory entry. And this has no effect on the file-handle hold by nohup.

out=$(mktemp -p .)
nohup sh -c 'sleep 30 ; echo "hello world"' >> $out 2>&1 &
mv $out nohup_out_$!.txt
unset out
1
  • Thank you for the award :D and thank you for the late answer. This is the trick I have searched for. It is a pleasure for me to mark this now as the accepted answer.
    – colidyre
    Jul 5, 2023 at 22:28
1

No. You can't save the PID of the command in the name of the file you're redirecting the output of that command to.

The reason for that is quite simple, your shell opens the file assigned with > or >> before it runs the command. There is no PID yet.

2
  • Maybe there is a trick getting the next pid which will be assigned?
    – colidyre
    Aug 8, 2018 at 14:49
  • Although PID's are sequential there is no feasible way to predict with certainty the PID a process will get assigned by the kernel
    – HBruijn
    Aug 8, 2018 at 14:55

You must log in to answer this question.

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