Pergunta

I have a Bash script which basically looks like this:

#!/bin/bash

command_1 &

command_a &
command_b &
command_c &

wait

echo "done"

I execute some commands in background using & at the end of the command. Then I wait for the commands to finish with wait. But I only want to wait for the commands a, b and c, not for 1. How can I do this? Is it possible to accomplish without collecting the PIDs of command a, b and c in an array and wait for those PIDs`? (That's what I tried so far, but it is kind of complicated.).

Foi útil?

Solução

You could execute commands a, b, c in a subshell.

command_1 &

( command_a & command_b & command_c & wait )

echo "done"

If you do not want to execute a, b, c in a subshell, then you need to keep track of the individual PIDs.

Outras dicas

To complete the list of answers, here is my "old" solution with collecting PIDs:

I execute every command (or a couple of commands) in a subshell and store the PID in an array. After I started all commands, I loop over my array and wait for each PID:

#!/bin/bash

INDEX=0

command_1 &

(
    command_a
) &

PIDS[$INDEX]=$!
INDEX=$[INDEX + 1]

(
    command_b
    command_c
) &

PIDS[$INDEX]=$!
INDEX=$[INDEX + 1]

for job in ${PIDS[@]}
do
    echo "wait for $job"
    wait $job
done

echo "done"

command_1 &
command_a & wait_pids+=($!)
command_b & wait_pids+=($!)
command_c & wait_pids+=($!)
wait "${wait_pids[@]}"
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top