【问题标题】:Bash script to read ids from file and spawn process in a controlled mannerBash 脚本以受控方式从文件中读取 ID 并生成进程
【发布时间】:2018-05-03 06:25:34
【问题描述】:

我需要从一个文件中读取数百个 id,并将它们作为参数传递给另一个 shell 脚本,以作为单独的子请求生成。 [完成]

但我们不能产生超过 6 个子请求,即在给定时间点运行的请求不能超过 6 个。

我浏览了这个站点(下面给出了参考资料)和其他站点,并了解到您可以使用 $!但距离实现它还很遥远,因为我不知道如何将它们存储在一个数组中,并在生成的过程完成后将其删除。

Forking / Multi-Threaded Processes | Bash

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

#!/bin/bash
file="/usr/share/nginx/html/cron/userids.txt" //file containing the userids that needs to be spawned

MAXCOUNT=6 //maximum number of child request that can be spawned

while IFS= read -r line
do
    #submit a background job here

    sh fetch.sh $line & //this is the shell script that needs to be submitted

    //check if the spawned request count is less than MAXCOUNT
    //If it is then wait for one or more request to finish 
    //If the number of child requests is less than MAXCOUNT then spawn another request 
    //if all the lines are read then wait till all the child process completes and then exit

done <"$file"

请注意,我是新手,对shell进程了解不多。

将不胜感激任何指示和反馈。

谢谢

【问题讨论】:

    标签: bash shell unix


    【解决方案1】:

    您可以为此使用 GNU Parallel

    parallel -j6 -a "$file" fetch.sh
    

    它有很多用于处理故障、进度条、日志记录等的选项。

    【讨论】:

    • 经历了这个,它似乎可以解决我面临的问题。在我运行它安装它之后,它显示一个错误,因为我试图执行的文件是“权限被拒绝”。我在 Ubuntu 上,我也可以从命令行运行上述包,但是使用 parallel 它会引发错误。有什么建议?在运行之前是否需要为 parallel 配置任何其他内容。
    • 我猜你没有在脚本的第一行放一个 shebang。或者您还没有使用chmod +x script.sh 使您的脚本可执行。要么做这两件事,要么使用sh script.sh 代替script.sh
    • 发现问题。将代码移动到另一个地方,它现在可以工作了。
    【解决方案2】:

    您可以使用xargs 生成最大数量的进程来传递从标准输入读取的参数

    xargs -n 1 -P 6 fetch.sh < "$file"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-30
      • 2019-08-03
      • 2012-07-13
      • 2020-06-18
      • 2021-05-16
      • 2014-10-26
      相关资源
      最近更新 更多