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

我试过了

prog1 
prog2

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

那么如何并行运行呢?


当前回答

这对我来说非常有用(在这里找到):

sh -c 'command1 & command2 & command3 & wait'

它混合输出每个命令的所有日志(这是我想要的),并使用ctrl+c杀死所有日志。

其他回答

你的脚本应该是这样的:

prog1 &
prog2 &
.
.
progn &
wait
progn+1 &
progn+2 &
.
.

假设你的系统一次可以处理n个任务。使用wait一次只运行n个作业。

你可以使用wait:

some_command &
P1=$!
other_command &
P2=$!
wait $P1 $P2

它将后台程序pid分配给变量($!是最后启动进程的PID),然后wait命令等待它们。这很好,因为如果您终止了脚本,它也会终止进程!

有一个非常有用的程序调用nohup。

     nohup - run a command immune to hangups, with output to a non-tty

我最近遇到了类似的情况,我需要同时运行多个程序,将它们的输出重定向到独立的日志文件中,然后等待它们完成,最后我得到了这样的结果:

#!/bin/bash

# Add the full path processes to run to the array
PROCESSES_TO_RUN=("/home/joao/Code/test/prog_1/prog1" \
                  "/home/joao/Code/test/prog_2/prog2")
# You can keep adding processes to the array...

for i in ${PROCESSES_TO_RUN[@]}; do
    ${i%/*}/./${i##*/} > ${i}.log 2>&1 &
    # ${i%/*} -> Get folder name until the /
    # ${i##*/} -> Get the filename after the /
done

# Wait for the processes to finish
wait

来源:http://joaoperibeiro.com/execute-multiple-programs-and-redirect-their-outputs-linux/

并行运行多个程序:

prog1 &
prog2 &

如果你需要脚本等待程序完成,你可以添加:

wait

在您希望脚本等待它们的地方。