0

Is there a way to force command substitution to exit leaving baground task undone?

Example:

cat test.sh
#! /bin/bash
sleep 5 &
echo "foo bar"

Running it without command substitution:

time bash test.sh
foo bar

real    0m0.005s
user    0m0.005s
sys 0m0.000s

With command substitution:

time echo $(bash test.sh)
foo bar

real    0m5.004s
user    0m0.002s
sys 0m0.000s
Tiago Lopo
  • 7,619
  • 1
  • 30
  • 51

1 Answers1

3

You need to redirect stdout and stderr for sleep:

#! /bin/bash
sleep 5 >/dev/null 2>&1 &
echo "foo bar"

bash command substitution on a script that executes a background task

Community
  • 1
  • 1