在一个脚本中并行运行相同的脚本

问题描述 投票:0回答:1

我有 CSV 文件中的文件列表。

FileList.CSV
QWE
ASD
ZXV
POI
LKJ
MNB

我必须运行脚本(Parent.sh),它将并行调用另一个脚本(Child.sh)(2级),该脚本从 FileList.CSV 获取参数

Parent.sh
Child.sh QWE &
Child.sh ASD &

条件: QWE 和 ASD 将并行运行,一旦其中任何一个完成,它将从 csv 文件中选择另一个参数

Parent.sh 将运行,直到处理完 csv 文件中的所有参数。

知道如何实现这一目标吗

shell unix sh
1个回答
0
投票

首先创建一个示例

child.sh
,该示例可能需要可变的处理时间

#!/bin/bash
((delay=RANDOM%3 +1))
echo "Processing $1 over $delay seconds"
sleep $delay
echo "Processed $1"

接下来使用

xargs
函数和
-P 2
(两个并行执行):

cat FileList.CSV | xargs -n1 -P2 ./child.sh

示例输出,我手动添加了

(1)
(2)

(1) Processing QWE over 3 seconds
(2) Processing ASD over 1 seconds
(2) Processed ASD
(2) Processing ZXV over 1 seconds
(2) Processed ZXV
(2) Processing POI over 2 seconds
(1) Processed QWE
(1) Processing LKJ over 3 seconds
(2) Processed POI
(2) Processing MNB over 1 seconds
(2) Processed MNB
(1) Processed LKJ

如果您想在最后一个孩子完成后看到提示,请添加

wait
:

cat FileList.CSV | xargs -n1 -P2 ./child.sh& wait
© www.soinside.com 2019 - 2024. All rights reserved.