Help us understand the problem. What is going on with this article?

シェルスクリプトで環境変数の一覧を取得する

More than 1 year has passed since last update.

環境変数の一覧が必要になったのでやり方を調べてみました。

結論

以下のコマンドで一覧を取得できます。

$ env -0 | tr '\r\n' ' ' | sed 's/\x0/\n/g' | sed 's/=.*//'

補足

env コマンドは以下のような形式で環境変数の一覧を出力します。

A=foo
B=bar
C='hoge
hoge'
...

ここから変数名だけ抜き出したいわけですが、上のC=のように値が複数行になる場合があります。
これをそのままsedで処理するのは難しいので、-0オプションをつけて出力をNull文字区切りにします。
trで改行を適当に置き換えてからNull文字を改行に置き換えれば値部分の改行だけ除去できるので、あとは=から行末まで消して終了です。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away