zshの環境変数について

実際 export
ってなにをやってるの?

export
とは
環境変数を設定するときによく使う。
export CMAKE_GENERATOR=Ninja
which
すると shell reserved word と出力される。echo
や [
とは異なる。
% which export
export: shell reserved word
% which echo
echo: shell built-in command
% which [
[: shell built-in command

export
の定義は?
export [ name[=value] ... ]
The specified names are marked for automatic export to the environment of subsequently executed commands. Equivalent to
typeset -gx
. If a parameter specified does not already exist, it is created in the global scope.
指定された名前は、その後に実行されるコマンドの環境に自動的にエクスポートされるようにマークされます。typeset -gx
と同等です。指定されたパラメータがまだ存在しない場合は、グローバル スコープで作成されます。The Z Shell Manual, 17 Shell Builtin Commands [1]

typeset -gx
とは?
typeset
Set or display attributes and values for shell parameters.
シェル パラメータの属性と値を設定または表示します。
-g
The
-g
(global) means that any resulting parameter will not be restricted to local scope. (略)
-g
(グローバル) は、結果のパラメータがローカル スコープに制限されないことを意味します。
-x
Mark for automatic export to the environment of subsequently executed commands. (略)
後で実行されるコマンドの環境への自動エクスポートをマークします。The Z Shell Manual, 17 Shell Builtin Commands

IEEE Std 1003.1-2024 (POSIX) によれば、 export
は 変数のエクスポート属性を設定する コマンドと定義されている[1]。この属性を付与された変数は、その後に実行されるコマンドの環境に含まれるようになる。

まとめると
- zsh
-
export
=typeset -gx
-
typeset -x
: 与えられた変数が その後に実行されるコマンドの環境に自動的にエクスポートされるようにする
-
- POSIX
-
export
は 変数のエクスポート属性を設定するコマンド - この属性が付与されると、その後に実行されるコマンドの環境に含まれるようになる
-
キーワードは エクスポート属性 と 環境

環境とは
ここまでポツポツと出てきた 環境 とはいったいなんなのか?

シェルは実行環境 command execution environment をもつ[1]。
環境は現在の作業ディレクトリやエイリアス、バックグラウンドジョブとそのPID、変数、関数などから構成される。ビルトインや関数を除くコマンドを実行する際は環境の一部がコピー、継承される。
上述のとおり、エクスポート属性を与えられた変数は継承の対象となる。つまり:
% N=1
% echo $N
1
% echo 'echo The value of N is $N' > script.sh && chmod +x script.sh
% ./script.sh
The value of N is # 普通の変数なので、継承されない
% export N
% ./script.sh
The value of N is 1 # エクスポート属性を与えたので、継承される
% typeset +x N
% ./script.sh
The value of N is # typeset +x でエクスポート属性を外したので、継承されない

まとめると
- シェルは 実行環境 をもつ
- シェルから普通のコマンドを実行するとき 環境の一部が継承(複製) される
- エクスポート属性を付与された変数は、継承の対象 となる
- つまり、環境変数 = エクスポート属性の付与された変数