linux - Bash 脚本并行处理有限数量的命令

我有一个如下所示的 bash 脚本:

#!/bin/bash
wget LINK1 >/dev/null 2>&1
wget LINK2 >/dev/null 2>&1
wget LINK3 >/dev/null 2>&1
wget LINK4 >/dev/null 2>&1
# ..
# ..
wget LINK4000 >/dev/null 2>&1

但是处理每一行直到命令完成然后移动到下一行非常耗时,例如我想一次处理 20 行,然后当它们完成时再处理 20 行。

我想过 wget LINK1 >/dev/null 2>&1 & 将命令发送到后台继续,但是这里有4000行这意味着我会有性能问题,而不是提到我应该同时启动多少个进程,所以这不是一个好主意。

我现在正在考虑的一个解决方案是检查其中一个命令是否仍在运行,例如在 20 行之后我可以添加这个循环:

while [  $(ps -ef | grep KEYWORD | grep -v grep | wc -l) -gt 0 ]; do
sleep 1
done

当然,在这种情况下,我需要将 & 附加到行尾!但我觉得这不是正确的做法。

那么我实际上如何将每 20 行组合在一起并等待它们完成,然后再转到接下来的 20 行,这个脚本是动态生成的,所以我可以在它生成的同时做任何我想做的数学运算,但它确实不必使用 wget,这只是一个示例,因此任何特定于 wget 的解决方案都不会对我有任何好处。

最佳答案

使用 wait 内置:

process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait

对于上面的例子,4 个进程 process1 ... process4 会在后台启动,shell 会等到这些进程完成后再开始下一组.

来自 GNU manual :

wait [jobspec or pid ...]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

https://stackoverflow.com/questions/19543139/

相关文章:

python - Pandas :从多级列索引中删除一个级别?

linux - 如何规范化 Bash 中的文件路径?

python - 如何在 Python 中将字符串转换为 double 值?

linux - 第一次如何配置postgresql?

python - 输入()错误 - NameError : name '...' is not de

linux - 如何将命令行参数传递给 unix/linux 系统上正在运行的进程?

python - 如何从文件中读取特定行(按行号)?

python - Google 大量使用 Python

linux - 如何获取进程 ID 以杀死 nohup 进程?

python - 在python中将 float 转换为整数的最安全方法?