linux - 并行运行 shell 脚本循环

标签 linux bash shell unix

我写了一个shell脚本

  1. 获取目录中所有图像文件的列表
  2. 如果需要新图像,请创建新文件夹
  3. 优化图像以节省存储资源

我尝试在mogrify之前使用parallel -j "$(nproc)"但发现是错误的,因为在mogrify之前使用的是DIR和mkdir,我需要在 mogrify 末尾添加类似 & 的内容,但仅针对 n 进程执行此操作。

当前代码如下:

#!/bin/bash

find $1 -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -type f | while read IMAGE
do
    DIR="$2"/`dirname $IMAGE`
    echo "$IMAGE > $DIR"
    mkdir -p $DIR
    mogrify -path "$DIR" -resize "6000000@>" -filter Triangle -define filter:support=2 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB "$IMAGE"
done

exit 0

有人可以建议并行运行此类脚本的正确方法是什么吗?因为每次运行大约需要 15 秒。

最佳答案

当您有一个 shell 循环进行一些设置并调用昂贵的命令时,并行化它的方法是使用 GNU 并行中的 sem:

for i in {1..10}
do
  echo "Doing some stuff"
  sem -j +0 sleep 2
done
sem --wait

这允许循环正常运行并执行其操作,同时还安排命令并行运行(-j +0 每个 CPU 核心运行一项作业)。

关于linux - 并行运行 shell 脚本循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839399/

相关文章:

linux - bash 变量的奇怪行为

python - 删除同一目录下多个 CSV 文件中的前两列和最后一列

linux - 在脚本中执行 cqlsh

bash - 如何从 stdin 读取多行输入到变量中以及如何在 shell(sh,bash) 中打印出一个?

c - 如何在带有 C 的 Linux 中使用伪终端?

java - Debian/etc/init.d/script 没有运行?

python - 计算文本文件中的不同单词 : different results in Shell and Python

php - 如何通过 brew 在 macOS 上安装和使用 PHP

linux - 如何从 swf 文件中提取随机屏幕截图?在Linux中

linux - 将文本文件中的一行复制到 shell