Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@f0o0o

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

方法

#!/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 を返す.

参考

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
1
Help us understand the problem. What are the problem?