1

I am using this approach to run a process in background.

"$@" &>/dev/null &disown

How do I achieve the following -

  1. Get the background pid
  2. Return it so that it can be consumed in another script?
5

The process ID of the most recently started background job is available to the shell as $!.

You may, for example output it to a file or to standard output:

"$@" &>/dev/null &
disown

printf '%d\n' "$!" >background.pid

Another script may then

./first-script.sh some command line

thepid=$( <background.pid )

Alternatively, if the first script just outputs the process ID to standard output, the second script could

thepid=$( ./first-script.sh some command line )
| improve this answer | |
  • The hardcoding to background.pid is restrictive no? I think we should just print to stdout and whoever wants it can just use it including >background.pid outside? I guess you mentioned that just to show that it is possible to write a file as well. – Nishant Feb 11 '17 at 16:31
  • 1
    @Nishant Yes, I just picked that filename out of thin air. Printing it to stdout or doing whatever else you want to do with it is up to you. – Kusalananda Feb 11 '17 at 16:33
  • @Nishant See edited answer. – Kusalananda Feb 11 '17 at 16:38
  • Yes. I was in the process of figuring that out, now its a matter of copy-paste :). Thanks! – Nishant Feb 11 '17 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.