Search code examples
linuxbashshellstdoutpid

BASH: Run script.sh in background and output that instance's pid to file?


I'm sure this is probably a shamefully daft question, but it feels like I've done two laps of the web reading things about process management, output redirection etc. but I'm struggling to make sense of it all enough to achieve what I'd like.

In essence:

I want to run a shell script (with some arguments passed when it's called) in the background; and as it runs, write the pid of that instance to a specified file.

./offtimer.sh device1 10 &

of course runs the script in the background, and outputs that instance's pid to the screen; I'd just like to get that number into a file (eg. device1.pid).

I know (by reading as well as trial & error, I promise!) that

./offtimer.sh device1 10 & > device1.pid

isn't valid syntax; but despite thread after thread I've read, I can't figure out a way to do it.

Sincerely grateful for any help!

R


Solution

  • You can access the last child process ID using $!.

    ./offtimer.sh device1 10 &
    echo $! > device1.pid