環境変数の最大長はどれくらい?
https://4.bp.blogspot.com/-HCSgYSu0yBc/WtWkOFGhuNI/AAAAAAABLpU/QHlMIEMJ8dI194OytT-IZyzQbqu8QpCrgCLcBGAs/s450/video_text_scroll_douga.png
まとめ
環境によるが何もしないとおそらく多くのLinux環境で128KBになる。 環境変数自体はなさそうだが一方で実行コマンドの最大長は設定されているので実質的にこれが制限値になる。
code:sh
echo | xargs --show-limits
Your environment variables take up 1660 bytes
POSIX upper limit on argument length (this system): 2093444
POSIX smallest allowable upper limit on argument length (all systems): 4096
Maximum length of command we could actually use: 2091784
Size of command buffer we are actually using: 131072 ← これ (つまり128KB)
Maximum parallelism (--max-procs must be no greater): 2147483647
調べてみた
雑に行けるギリギリをせめて見る。
code:sh
# 131000byte のダミーデータを作る
cat /dev/urandom | base64 | head -c 131000 > ./dummy
# 環境変数にダミーデータを入れ込む
export X="$(cat ./dummy)"
# 環境変数を出力して文字数をカウント
echo -n "$X" | wc -c
131000
行けないギリギリあたりを攻める
code:sh
# 131072byte のダミーデータを作る
cat /dev/urandom | base64 | head -c 131072 > ./dummy
# 環境変数にダミーデータを入れ込む
export X="$(cat ./dummy)"
# 環境変数を出力して文字数をカウント
echo -n "$X" | wc -c
bash: /usr/bin/wc: Argument list too long # コマンド実行ができない
概ね xargs のレポートにあるような制限が適用されている。 go run とかでも同様だったので入力してるコマンドというより環境変数まで含んで評価されている様子であった。
128KBはどこから来るのか?
execve(2) のマニュアルにこの値に関係ありそうな制限の事項が書いてあった。
On Linux prior to kernel 2.6.23, the memory used to store the
environment and argument strings was limited to 32 pages (defined
by the kernel constant MAX_ARG_PAGES). On architectures with a
4-kB page size, this yields a maximum size of 128 kB.
ちなみにこの制限は execve の制限なので、プロセスをフォークしない使い方に限定できればより大きな環境変数を用いて操作ができるが、 execve を避けてアレコレすることは非常に困難だと考えられるため、やはり事実上多くの環境下で 128KB と考えておくのが良さそう。
関連情報