2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

シェルスクリプトでwhile readが1行目しか処理してくれない

Posted at
cat foo.txt | while read line; do
    hogehoge
done

こんなスクリプトがあったとして、2行目以降が処理されないことがあります。そんな問題の解決策です。

結論

私の場合の解決策は以下の通りでした。

cat foo.txt | while read line; do
    hogehoge < /dev/null
done

ループの中の標準入力を /dev/null にしてしまいます。

なにがおきているか

hogehoge のが標準入力を吸い込んでしまう場合に2行目が実行されません。 while read が読み取るべき2行目以降を hogehoge が消化してしまうのです。

具体的には ssh コマンドがよくこの問題に当たります。 Dockerで動かしているツールでも起き得ます。

hogehoge がまた別のシェルスクリプトのファイルを実行し、その中に sshdocker run などがある場合でも同じことが起きます。

補足

ループの中身が大きくて、どのコマンドが標準入力を横取りしてしまっているのか不明な場合は、次のようにします。

cat foo.txt | while read line; do (
    hogehoge1
    hogehoge2
    hogehoge3
) < /dev/null; done
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?