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
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. Commented Nov 28, 2014 at 17:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.