0
3

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 5 years have passed since last update.

子プロセスとシェル変数

Last updated at Posted at 2019-12-27

子プロセスとシェル変数

シェルスクリプトのシェル変数の値に関するメモ。
パイプや括弧を使うと変数の範囲が変わるという話。

はじめに

本稿で使用するCSVファイルは以下で作成。

$ seq 1 5 > hoge.csv

<とwhile readで読み込む場合

  • サンプルコード
sample1.sh
# !/bin/bash

i=0

while read line
do
  i=$((i + 1))
done < hoge.csv

echo $i
  • 実行結果
$ ./sample1.sh
5

catとwhile readで読み込む場合

  • サンプルコード
sample2.sh
# !/bin/bash

i=0

cat hoge.csv | while read line
do
  i=$((i + 1))
done

echo $i
  • 実行結果
$ ./sample2.sh
0

パイプを使うと子プロセスになるので、外側のiは0で初期化したまま結果が0となる。
子プロセスは親の値を引き継ぎ、その後はその中でだけ使用される。

catとwhile read、()で読み込む

  • サンプルコード
sample3.sh
# !/bin/bash

i=0

cat hoge.csv | ( while read line
do
  i=$((i + 1))
done

echo $i
)
  • 実行結果
$ ./sample3.sh
5

()または{}で囲えばその中は同じプロセスとなる。
()と{}の違いは子プロセスにするかどうか。

()は子プロセス、{}は現プロセスでまとめる。

sample4.sh
# !/bin/bash

hoge(){ echo '$$:' $$ ' $BASHPID:' $BASHPID; }
fuga()( echo '$$:' $$ ' $BASHPID:' $BASHPID )

echo '$$:' $$ ' $BASHPID:' $BASHPID
hoge
fuga
  • 実行結果
$ ./sample4.sh
$$: 17721  $BASHPID: 17721
$$: 17721  $BASHPID: 17721
$$: 17721  $BASHPID: 17722
0
3
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
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?