gpt4 book ai didi

shell - 在 shell 中并行化多个相似程序实例的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-28 21:31:34 25 4
gpt4 key购买 nike

我有一个运行测试的程序,它需要很多参数。假设我有调用 test.sh 的程序 main.sh,它是测试程序。在 main.sh 中,我为要运行的 test.sh 添加了许多不同的参数。只运行一个测试没有问题。

但是,shell 允许我使用 & 同时运行多个实例。我正在考虑使用 for 循环通过 & (后台运行)多次调用此测试,并在循环开始时设置不同的参数。它看起来像下面这样:

#main.sh
for i in 0 1 2 3; do
value=${param[$i]}
#test.sh takes "value" as a parameter inside it and run
. ./test.sh &
done

但是,test.sh 通常需要一段时间才能完成,并且会多次使用参数值。在这种情况下,当循环继续运行并递增“i”以更改参数值时,test.sh 的初始实例将采用不同的参数并且循环保持在进行中。有没有办法让 test.sh 以不变的参数值运行任何程序实例?

最佳答案

您的子脚本 test.sh 将拥有父环境的副本,因此更改父环境中的父数据不会影响它(只要您运行它作为一个进程,不是通过点运算符)。您可以通过两种方式做到这一点:

  • test.sh命令行传递参数
  • 在启动 test.sh 之前导出环境变量

无论哪种情况,这都不会影响您之前启动的 test.sh 实例。

更具体地说,尝试:

for i in 1 2 3 4; do
value=${param[$i]}
./test.sh $value & # value is passed as command-line parameter
done

关于shell - 在 shell 中并行化多个相似程序实例的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598878/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com