我有一个如下所示的 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/