Search code examples
bashcommand-substitution

Command substitution and undone background tasks


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

Solution

  • 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