1

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

asked Feb 25, 2015 at 1:18

3 Answers 3

4

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

./offtimer.sh device1 10 &
echo $! > device1.pid
answered Feb 25, 2015 at 1:22
Sign up to request clarification or add additional context in comments.

2 Comments

Sincerest thanks! I imagined it'd be straightforward, but it's not easy until one knows how! - I'd seen $! in some heavy examples, but couldn't pick out what it was up to. Thanks again!
@RobB when in doubt the Bash manual is pretty solid if not a little long - gnu.org/software/bash/manual/html_node/Special-Parameters.html
0

$! is the last background process's ID.

./offtimer.sh device1 10 &
echo $! > device1.pid
answered Feb 25, 2015 at 1:24

Comments

-1

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

Alternatively you could write that to the file within the script rather than output it to stdout.

answered Feb 25, 2015 at 1:23

1 Comment

This does not work. It would redirect the stdout of ./offtimer.sh device1 10 to device1.pid

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.