Help us understand the problem. What is going on with this article?

bash で複数プログラムを同時に走らせる

More than 1 year has passed since last update.

方法

#!/usr/bin/env bash
set -e

for index in {1..5}; do
    ./run.sh $index &
    pids[$index]=$!
done

for pid in ${pids[*]}; do
    wait $pid
done

のようにすればよい.

補足

基本的には, 同時に走らせたいプログラムをバックグラウンド実行して wait で待てばいい.
例えば,

run_all.sh
#!/usr/bin/env bash
set -e

run0.sh &
run1.sh &
wait

のようにする.
ただし, これだとバックグラウンド実行したプログラムでエラーが起きても, wait が exit code 0 を返すので, エラーが起きたかが分からない.

エラーが起きたかを知るには, wait で PID を指定するようにすれば良い.
直前に実行したコマンドの PID は $! で取得できる.
例えば,

run_all.sh
#!/usr/bin/env bash
set -e

./run0.sh &
pids[0]=$!
./run1.sh &
pids[1]=$!

wait ${pids[0]}
wait ${pids[1]}

のようにすれば, run0.shrun1.sh でエラーが起きた時, run_all.sh も exit code 1 を返す.

参考

f0o0o
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした