3

I'd like to return the results of a script that also kicks off a background task. The command substitution operator waits for the background task, making the call slow. I created the following example to illustrate the problem:

function answer {
    sleep 5 &
    echo string
}

echo $(answer)

Is there a way to call a command without waiting on any background jobs it creates?

Thanks,

Mark

chepner
  • 497,756
  • 71
  • 530
  • 681

2 Answers2

3

The problem is that sleep inherits stdout and keeps it open. You can simply redirect stdout:

answer() {
  sleep 5 > /dev/null &
  echo "string"
}
echo "$(answer)"
that other guy
  • 116,971
  • 11
  • 170
  • 194
0

If you are intending for the program to continue merrily along in the mean time while the function works, you can just call the function to run in the background.

function answer {
    sleep 5
    echo Second
}

echo $(answer) &
echo First

The output of which will be

First
Second
Jonathan Wheeler
  • 2,539
  • 1
  • 19
  • 29