BashシェルスクリプトからPIDを取得する方法

BashシェルスクリプトからPIDを取得する方法

Dockerコンテナを使用して複数のサブタスクを送信する次のコードがあります。

#!/bin/bash

for file in "all files of a given type"; do 
     docker exec -itd "docker container" "command to be executed within docker container" &
done

pidlist=$(pgrep -f "command to be executed within docker container")

for pid in $pidlist; do
    echo $pid
    wait $pid
done

私の目標は、すべてのサブタスクが完了するまでスクリプトが終了するのを待つことです。このスクリプトは、他のコマンドやスクリプトを含む大きなスクリプトの一部であるため、これが必要です。

しかし、私が取得したPIDは、サブタスクを見つけるために端末でtopを使用するときとは異なるため、すべてのサブタスクが送信された後にスクリプトが終了します。

ベストアンサー1

明示的なpidを待つ必要はありません。スクリプトがいくつかのバックグラウンドプロセスを開始するだけであれば、すべてが完了するのを待つことができます。次のようにしてみてください。

#!/bin/bash
for file in "all files of a given type"; do 
    docker exec -itd "docker container" "command to be executed within docker container" &
done

wait

この変更されたバージョンのスクリプトは、いくつかのバックグラウンドプロセスを開始してから、すべてのプロセスが終了するのを待ちます。

おすすめ記事