本文介绍了在bash中并行设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例程序:

#!/bin/bash

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

wait

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

我希望它能够运行并打印出分配给output数组的每个成员的值,但是它什么也不打印.正确删除&会分配变量.我必须使用不同的语法来并行实现吗?

I would expect this to run and print out the values assigned to each member of the output array, but it prints nothing. Removing the & correctly assigns the variables. Must I use different syntax to achieve this in parallel?

推荐答案

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

whole 分配放在后台任务(子流程)中,这就是为什么您看不到结果的原因,因为它没有传播到父流程中.

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)

这篇关于在bash中并行设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 00:24
查看更多