简体   繁体   English

shell脚本运行多个文件

[英]shell script run multiple files

I want to use a shell scrip in a for-loop that run 100 files in parallel. 我想在for循环中使用shell脚本,并行运行100个文件。

Currently, I have a shell script of the following format: 目前,我有一个以下格式的shell脚本:

#!/bin/bash
NUM=10
python a1.py $((NUM + 0)) &
python a2.py $((NUM + 2)) &
python a3.py $((NUM + 4)) &
python a4.py $((NUM + 6)) &
python a5.py $((NUM + 8)) &

Now, if I have a1.py , a2.py , a3.py .... a100.py , and I want to run them in parallel, how do I do it in for-loop? 现在,如果我有a1.pya2.pya3.py .... a100.py ,并且我想并行运行它们,我该如何在for循环中执行它?

If you have bash version 4 and run this: 如果您有bash版本4并运行此:

echo {10..208..2} 

You will get this: 你会得到这个:

10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60
62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100 102 104 106 108 
110 112 114 116 118 120 122 124 126 128 130 132 134 136 138 140 142 144 146 
148 150 152 154 156 158 160 162 164 166 168 170 172 174 176 178 180 182 184 
186 188 190 192 194 196 198 200 202 204 206 208

which looks like your series. 看起来像你的系列。 Then, if you want to run lots of jobs in parallel, I would use GNU Parallel . 然后,如果你想并行运行大量的工作,我会使用GNU Parallel That offers you {#} as a placeholder for the job number. 这为您提供{#}作为职位编号的占位符。 So, if you run this: 所以,如果你运行这个:

parallel -k echo {#} {} ::: {10..208..2}

You will get this: 你会得到这个:

1 10
2 12
3 14
4 16
5 18

So, to run your actual scripts, something like: 因此,要运行您的实际脚本,例如:

parallel -k --dry-run 'python a{#}.py {}' ::: {10..208..2}

Sample Output 样本输出

python a1.py 10
python a2.py 12
python a3.py 14
python a4.py 16
...
...

If that looks good, run again without the --dry-run and without the -k which keeps the output in order to make it easier to debug. 如果看起来不错,请在没有--dry-run情况下再次--dry-run并且不使用-k来保持输出,以便更容易调试。

TLDR; TLDR;

My most concise answer, with GNU Parallel is: 我最简洁的答案是GNU Parallel

parallel python a{#}.py {} ::: {10..208..2}

Or if you don't have bash version 4: 或者如果你没有bash版本4:

parallel python a{#}.py {} ::: $(seq 10 2 208)
NUM=10
for ((i=0; i<100; i++)); do echo python a$(($i+1)).py $(($NUM+$i*2)); done

Output: 输出:

python a1.py 10
python a2.py 12
python a3.py 14
.
.
.
python a98.py 204
python a99.py 206
python a100.py 208

If this looks okay, use: 如果这看起来没问题,请使用:

NUM=10
for ((i=0; i<100; i++)); do python a$(($i+1)).py $(($NUM+$i*2)) & done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM