0
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?

Bashにおける環境変数のスコープ

Last updated at Posted at 2025-11-01

Bashスクリプトで複数シェル間の変数を扱う場合、「環境変数のスコープ」がどの範囲に影響するのか理解することは非常に重要です。本記事では、Bash公式資料に基づいて整理し、具体例を交えて解説します。

  1. Bashにおける変数の種類とスコープ
    Bashの変数は大きく分けて以下の3種類があります。
変数の種類 定義方法 親シェルで見える 子プロセスで見える 備考
ローカル変数 VAR=value × デフォルトでプロセス内のみ有効
環境変数 export VAR=value 子プロセスに引き継がれる
一時的な環境変数 VAR=value command ○ (command内) コマンド実行後は消える

公式資料(Bash Reference Manual: Shell Variables)では、
Shell variables are local to the shell in which they are defined, but may be exported to the environment of child processes.
と記載されており、exportしない限り子プロセスには影響しません。

典型的な利用ケース

ケース1:親シェルで変数を定義し、サブシェルで使用する

VAR1=hello
export VAR2=world

# サブシェル
( echo "VAR1=$VAR1"; echo "VAR2=$VAR2" )

出力:

VAR1=
VAR2=world

VAR1はローカル変数なのでサブシェルには渡らない
VAR2はexportされているのでサブシェルに渡る

ケース2:パラメータファイルを読み込み、別シェルに引数として渡す

A.sh
# XXXパラメータファイルを読み込み
source XXX.sh  # XXX.sh 内で export VAR_NAME=value
# 値を上書き
VAR_NAME=new_value

# B.sh を引数付きで起動
./B.sh "$VAR_NAME"

複数回 A.sh を起動しても、それぞれ独立したプロセスとして動作
環境変数は A.sh のプロセスとその子プロセス(B.sh)にのみ有効
他の A.sh のプロセスには影響しない

公式資料では:
When a command is executed, the shell makes available its environment variables to that command. Variables may be marked for automatic export to the environment of subsequently executed commands using the export built-in.

とあり、exportのスコープは「プロセス単位」であることが明示されています。

補足

コマンドおよびサブシェルは表面的に異なるだけで親プロセスの子プロセス。
また、環境変数が子プロセスに渡されます。

シェル組み込みコマンド(echo, cd など)

まとめ

Bashの変数は デフォルトでローカル
export すると 子プロセスに引き継がれる
複数プロセス間で変数は共有されない
子プロセスに値を渡す場合は 引数や一時的な環境変数 を利用可能

追記[20251102]

Git Bash での実行結果

VAR1=hello
export VAR2=world
( echo "VAR1=$VAR1"; echo "VAR2=$VAR2" )

Git Bash でベタ打ちすると VAR1 も VAR2 も表示されたことを確認しました。

Linux 標準挙動で確認した結果

VAR1=hello
export VAR2=world

bash -c 'echo "VAR1=$VAR1"; echo "VAR2=$VAR2"'
結果
VAR1=
VAR2=world
0
0
2

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
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?