Saving a process ID when detaching a command in Bash

4

2

When I detach command:

$ command &

The result is a printout to STDOUT:

[1] < PID >

I would like to monitor this PID. However, I cannot write this output anywhere but STDOUT! How can I redirect this to a file or a variable?

I have tried:

$ command 1> ./temp.txt &

But this still finds its way to STDOUT!

Thanks in advance for the help!

Daeden

Posted 2013-07-17T00:35:51.857

Reputation: 161

Answers

11

$! should contain the PID of the last background process. Something like...

$ command &
$ echo $! > temp.txt

Should give you a file named temp.txt with the PID in it.

Or on one line...

$ command & echo $! > temp.txt

Bill Heller

Posted 2013-07-17T00:35:51.857

Reputation: 981

Awesome. This does not answer my exact question, but this is even better! – Daeden – 2013-07-17T06:44:25.553

Yeah, I think the problem is stdout is the output of the command you're running, but the id is coming from the shell. So to capture it with stdout you'd have to actually execute it in a subshell some how and capture the stdout of that. Just thinking out loud about what's going on, haven't tested that. – Bill Heller – 2013-07-17T14:29:53.970