3

I am trying to write a bash script that collects numerical results returned by several commands, and then does some simple arithmetic on the results. It would be great if the commands (which are independent) could run in parallel. The following works fine without the “&”, and takes 10 seconds. With the “&”, it takes 5 seconds as expected, but then gives the error message below. Grateful for any suggestions.

#!/bin/bash
set -eu
echo "Running .."
aa=$(sleep 5; ls |wc -l) & ###try with and without <&>
bb=$(sleep 5; ls |wc -l) & ###try with and without <&>
wait
cc=$(($aa + $bb))
echo $cc

run.sh: line 7: aa: unbound variable
David H
  • 31
  • 1
  • @KarolyHorvath suggested the link a second before I submitted the same :P As shown there, you'll have to use a different method to capture the output. – outlyer Nov 28 '14 at 17:58

1 Answers1

5

The & doesn't just affect the contents of the parens, it affects the whole command. Which is to say that it affects the assignment itself.

But what does & actually do? It runs the command in a separate process. One where variable assignments don't get reflected to the parent shell. Which means that even after running for 5 whole seconds the command accomplishes absolutely nothing other than running the commands in parens.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358