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

我试过了

prog1 
prog2

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

那么如何并行运行呢?


当前回答

#!/bin/bash
prog1 & 2> .errorprog1.log; prog2 & 2> .errorprog2.log

将错误重定向到单独的日志。

其他回答

你可以试试ppss(废弃)。PPSS非常强大——你甚至可以创建一个迷你集群。 如果您有一批令人尴尬的并行处理要做,xargs -P也很有用。

使用bashj (https://sourceforge.net/projects/bashj/),您不仅可以运行多个进程(其他人建议的方式),还可以在一个JVM中运行多个线程,这些线程由您的脚本控制。当然,这需要java JDK。线程比进程消耗更少的资源。

下面是一个工作代码:

#!/usr/bin/bashj

#!java

public static int cnt=0;

private static void loop() {u.p("java says cnt= "+(cnt++));u.sleep(1.0);}

public static void startThread()
{(new Thread(() ->  {while (true) {loop();}})).start();}

#!bashj

j.startThread()

while [ j.cnt -lt 4 ]
do
  echo "bash views cnt=" j.cnt
  sleep 0.5
done

这里有很多有趣的答案,但我从这个答案中获得了灵感,并将一个简单的脚本组合在一起,并行运行多个进程,并在完成后处理结果。你可以在以下要点中找到它:

#!/usr/bin/env bash

# inspired by https://stackoverflow.com/a/29535256/2860309

pids=""
failures=0

function my_process() {
    seconds_to_sleep=$1
    exit_code=$2
    sleep "$seconds_to_sleep"
    return "$exit_code"
}

(my_process 1 0) &
pid=$!
pids+=" ${pid}"
echo "${pid}: 1 second to success"

(my_process 1 1) &
pid=$!
pids+=" ${pid}"
echo "${pid}: 1 second to failure"

(my_process 2 0) &
pid=$!
pids+=" ${pid}"
echo "${pid}: 2 seconds to success"

(my_process 2 1) &
pid=$!
pids+=" ${pid}"
echo "${pid}: 2 seconds to failure"

echo "..."

for pid in $pids; do
        if wait "$pid"; then
                echo "Process $pid succeeded"
        else
                echo "Process $pid failed"
                failures=$((failures+1))
        fi
done

echo
echo "${failures} failures detected"

结果是:

86400: 1 second to success
86401: 1 second to failure
86402: 2 seconds to success
86404: 2 seconds to failure
...
Process 86400 succeeded
Process 86401 failed
Process 86402 succeeded
Process 86404 failed

2 failures detected

你的脚本应该是这样的:

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

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

由于某些原因,我不能使用等待,我想出了这个解决方案:

# create a hashmap of the tasks name -> its command
declare -A tasks=(
  ["Sleep 3 seconds"]="sleep 3"
  ["Check network"]="ping imdb.com"
  ["List dir"]="ls -la"
)

# execute each task in the background, redirecting their output to a custom file descriptor
fd=10
for task in "${!tasks[@]}"; do
    script="${tasks[${task}]}"
    eval "exec $fd< <(${script} 2>&1 || (echo $task failed with exit code \${?}! && touch tasks_failed))"
    ((fd+=1))
done

# print the outputs of the tasks and wait for them to finish
fd=10
for task in "${!tasks[@]}"; do
    cat <&$fd
    ((fd+=1))
done

# determine the exit status
#   by checking whether the file "tasks_failed" has been created
if [ -e tasks_failed ]; then
    echo "Task(s) failed!"
    exit 1
else
    echo "All tasks finished without an error!"
    exit 0
fi