Set variables in parallel in bash

后端 未结 2 1962
小蘑菇
小蘑菇 2021-01-20 20:53

Here\'s an example program:

#!/bin/bash

for x in {1..5}
do
  output[$x]=$(echo $x) &
done

wait

for x in {1..5}
do
  echo ${output[$x]}
done

2条回答
  •  萌比男神i
    2021-01-20 20:59

    This

    output[$x]=$(echo $x) &
    

    puts the whole assignment in a background task (sub-process) and that's why you're not seeing the result, since it's not propogated to the parent process.

    You can use wait to wait for subprocesses, but returning results (other than status codes) is going to be difficult. Perhaps you can write intermediate results to a file, and collect those results after all processes have finished ? (not nice, I appreciate)

提交回复
热议问题