如何使用bash脚本并行运行多个程序

问:

我正在尝试编写一个能同时运行多个程序的 .sh 文件。

我试过这个

prog1 prog2

但这会运行 prog1,然后等待 prog1结束,然后启动 prog2…

那么我如何并行运行它们呢?

答:

为了测试验证解决题主需求的程序,这里编写 prog1.sh 和 prog2.sh 两个脚本文件,prog1 内容如下:

for cnt in {1..5}; do
    sleep 1
    echo 'p1:' $(date +"%Y-%m-%d %H:%M:%S")
done

prog2 内容如下:

for ((i = 0 ; i < 5 ; i++)); do
  echo "p2:   " $(date +"%Y-%m-%d %H:%M:%S")
  sleep 2
done

使用命令 man bash 查阅手册,可见如下描述:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0.

于是便有了方式一,编写脚本文件 parallel.sh :

#! /usr/bin/env bash

./prog1.sh &
./prog2.sh &

wait

执行效果如下:

image-20230801102450922.

查阅 Bash Reference Manual 看到了 GNU Parallel,于是便有了方式二,测试效果如下:

image-20230801102540129

看到这里大家肯定奇怪,为什么这种方式的运行输出不像方式一中那样交替输出。使用命令 man parallel 查阅手册可知:parallel 会对输出进行分组,以便不同作业的输出不会混合。

方式三则是使用 xargs 命令传递参数给 bash,测试效果如下:

image-20230801102620354

其中参数 -n1 表示每次将 1 项作为命令行参数;-P2 表示一次同时最多使用两个进程,如果需要不限制进程数可改用参数 -P0。

参考:

posted @ 2023-08-01 10:34  寻梦99  阅读(198)  评论(0)    收藏  举报