Jordan Mackie
Jordan Mackie

Reputation: 2406

Run command in background and capture result later (Bash)

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!

Upvotes: 0

Views: 2676

Answers (1)

pynexj
pynexj

Reputation: 20688

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 )

Upvotes: 1

Related Questions