如何并行运行 bash 脚本

摩根·格拉登

我有一系列需要并行执行的 250 个 bash 脚本。每个脚本使用大约 1 个内核,所以我不想同时执行它们。我想同时运行 10 个脚本,每当一个脚本完成时执行另一个脚本。

保罗·霍奇斯

我推荐parallel,但我要发布这个怪物是为了让人们把它拆开并调整它。:)

#! /bin/env bash

## TODO: this documentation block needs to be expanded.
use="

  $0 <#procs> <cmdfile>

  Pass the number of desired processes to prespawn as the 1st argument.
  Pass the command file with the list of tasks you need done.

  Command file format:
   KEYSTRING:cmdlist

  where KEYSTRING will be used as a unique logfile name
  and   cmdlist   is the base command string to be run

  KEYSTRING may not contain whitespace of any sort.
  Other lines are not allowed, including blanks or comments.

"

die()  { echo "$@ $use" >&2; exit 1; }

case $# in
2) case "$1" in
   *[^0-9]*) die "INVALID #procs '$1'" ;;
   esac
   declare -i primer="$1"  # a countdown of how many processes to pre-spawn
   cmdfile="$2"
   [[ -r "$cmdfile" ]]  || { die "$cmdfile not readable"; }
   grep -v : "$cmdfile" || { die "$cmdfile has invalid lines"; }
   declare -i lines=$( grep -c : $cmdfile)
   if (( lines < primer ))
   then die "Note - command lines in $cmdfile ($lines) fewer than requested process chains ($primer)"
   fi  ;;
*) die ;;
esac >&2

trap 'echo abort $0@$LINENO; use; exit 1' ERR       # make sure any error is fatal
trap ': no-op to ignore' HUP  # ignore hangups (built-in nohup without explicit i/o redirection)

spawn() {
  IFS="$IFS:" read key cmd && [[ "${cmd:-}" ]] || return
  echo "$(date) executing '$cmd'; c.f. $key.log" | tee "$key.log"
  echo "# autogenerated by $0 $(date)
   { $cmd
     spawn
   } >> $key.log 2>&1 &
  " >| $key.sh
  . $key.sh
  rm -f $key.sh
  return 0
}

# create a command list based on those designators
declare chains=0
while (( primer-- ))  # until we've filled the requested quota
do spawn              # create a child process
done < $cmdfile

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

并行运行bash脚本?

来自分类Dev

从python脚本并行运行bash脚本

来自分类Dev

如何在bash脚本中禁用并行运行

来自分类Dev

并行运行脚本时Bash脚本未休眠

来自分类Dev

如何并行运行多个shell脚本?

来自分类Dev

从bash并行运行

来自分类Dev

锁定bash脚本以防止从脚本本身内部并行运行?

来自分类Dev

调用多个bash脚本并并行运行,而不是依次运行

来自分类Dev

bash脚本中的命令是并行运行还是一个接一个运行?

来自分类Dev

从bash并行运行多个脚本,而无需将输出打印到控制台

来自分类Dev

并行运行两个连续的bash脚本4次

来自分类Dev

并行运行多个具有不同名称的bash脚本

来自分类Dev

从bash并行运行多个脚本,而无需将输出打印到控制台

来自分类Dev

如何并行运行脚本的x个实例?

来自分类Dev

如何防止Perl脚本并行运行多次

来自分类Dev

如何防止Perl脚本并行运行多次

来自分类Dev

如何并行运行脚本的x个实例?

来自分类Dev

如何与Django并行运行自定义脚本

来自分类Dev

并行运行bash for循环

来自分类Dev

Powershell并行运行脚本

来自分类Dev

存储并行运行的PHP脚本的输出

来自分类Dev

查询重新并行运行循环脚本

来自分类Dev

如何并行运行许多PHP脚本并将每个脚本的输出重定向到文件?

来自分类Dev

bash脚本的并行执行

来自分类Dev

使用iPython并行运行bash命令

来自分类Dev

使用Bash并行运行任务

来自分类Dev

使用iPython并行运行bash命令

来自分类Dev

如何运行bash压缩脚本?

来自分类Dev

如何循环运行bash脚本