【问题标题】:launch several computation in batch in a shell在 shell 中批量启动多个计算
【发布时间】:2017-03-31 08:03:35
【问题描述】:

我有 16 个计算要做,我想批量启动它,以便同时使用我机器的 16 个内核。 我想做一个这样的shell脚本:

#!/bin/ksh
for i in `seq 16`
do
  cd directory$i
  <batch command>
done

有可能吗?

【问题讨论】:

    标签: linux shell ksh


    【解决方案1】:

    可以。您只需确保它们作为后台任务运行,例如:

    #!/bin/ksh
    for i in `seq 16`
    do
      cd directory$i
      <batch command> &
    done
    

    没有它,它只会按顺序运行作业。您可能还想确保您也等待它们全部完成,使用wait

    #!/bin/ksh
    for i in `seq 16` ; do
      cd directory$i
      <batch command> &
    done
    wait # May depends on shell, bash/ksh waits for all
    

    【讨论】:

    • 有必要做16个等待命令吗?在 man wait 我有: wait [n ...] 等待每个指定的进程并返回其终止状态。如果没有给出n,则等待所有当前活动的子进程,返回状态为零。所以在脚本结束时只需要等待 1 次吗?
    • @rudy:不确定ksh,但您似乎是对的(刚刚测试过)。 bashksh 都将等待所有当前活跃的孩子。如果您有其他孩子在该 16 人组中,那当然可能会引入另一个问题。如果是这样,您可能需要考虑存储 PID 并使用显式等待。
    【解决方案2】:

    无需反引号(外部命令)

    #!/bin/ksh
    for d in  dir{1..16}; do
        echo $d &
    done
    wait
    echo done
    

    btw schellcheck.net 会说:

    Use $(..) instead of legacy `..`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 2016-06-13
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多