0

Similar to these questions (1) (2), I'm wanting to run a command in a background process, carry on processing, then later use the return value from that command.

I have one function in my script that takes particularly long, so I would like to run it first before the rest of the setup so that there is less of a delay when the return value of that script is given, but currently the return value doesn't get captured.

What I've tried:

if [ $LAZY_LOAD -eq 0 ]; then
    echo "INFO - Getting least loaded server in background. Can take up to 30s."
    local leastLoaded=$( getLeastLoaded ) &
fi

# Other setup stuff that doesn't use leastLoaded...
# setup setup setup....

if [ $LAZY_LOAD -eq 0 ]; then
    echo "INFO - Waiting for least loaded server to be retrieved before continuing"
    wait

fi

echo "INFO - Doing stuff with $leastLoaded."
doThingWithLeastLoaded $leastLoaded

getLeastLoaded definitely works without the &, so I'm sure this is a concurrency issue.

Thanks!

Jordan Mackie
  • 2,264
  • 4
  • 25
  • 45
  • 1
    As far as I know, you cannot set a variable from a background job. Write the result to a temporary file or fifo. If you have a lot of jobs you want to execute in parallel, consider using `make` or GNU `parallel` – Socowi Jun 22 '18 at 10:36

1 Answers1

1

According to bash manual:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell.

So your local command would not affect the current shell.

I'd suggest like this:

do-something > /some/file &
... ...
wait
var=$( cat /some/file )
pynexj
  • 19,215
  • 5
  • 38
  • 56