3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ShellScriptでの並列実行は「&」で解決

Last updated at Posted at 2025-04-16

これまでは直列でしかShellScriptを書いてきてなかったんですが、並列での実行を必要とするケースに直面したので、備忘録として残しておきます。

登場人物

[並列実行させるスクリプトたち]
・script1.sh
・script2.sh

[実際に実行するスクリプト]
・execute.sh

スクリプトの中身

  • script1.sh
#!/bin/bash

sleep 3
echo "script1 : 3 seconds elapsed."
sleep 3
echo "script1 : 6 seconds elapsed."
  • script2.sh
#!/bin/bash

sleep 3
echo "script2 : 3 seconds elapsed."
sleep 3
echo "script2 : 6 seconds elapsed."
  • execute.sh
#!/bin/bash

date "+%Y-%m-%d %H:%M:%S"

# コマンド配列
commands=("./script1.sh" "./script2.sh")
for cmd in "${commands[@]}"; do
    # コマンドをバックグラウンドで実行
    eval "$cmd" &
done

# 全てのバックグラウンドプロセスが終了するまで待機
wait

date "+%Y-%m-%d %H:%M:%S"

実行

$ ./execute.sh
2025-04-16 19:38:16
script2 : 3 seconds elapsed.
script1 : 3 seconds elapsed.
script2 : 6 seconds elapsed.
script1 : 6 seconds elapsed.
2025-04-16 19:38:22

script1.sh, script2.shが並列で実行されていることがわかる。

最後に

> /dev/null &でバックグラウンド処理させることは多々あったのに、1つのスクリプト内で並列処理できるってことまで考えが至ってませんでした。

ただ、並列実行処理で標準出力させると、コンソールが荒れるので、リダイレクトさせておいて、wait後に一括で吐き出したほうがよさそうです。

参考

https://job-info.hateblo.jp/entry/2024/08/16/230606
xargsを利用するやり方もあるそう。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?