LoginSignup
1
0

More than 1 year has passed since last update.

【Linux】シェル変数と環境変数

Posted at

シェル変数と環境変数の違い

シェル変数は、実行中のシェルのみが使用する変数です。
環境変数は、実行中のシェルとそのシェルで起動したプログラム(子プロセス)等が使用する変数です。

image.png

シェル変数を定義する

シェル変数を定義するには、ターミナル上でシェル変数名=値と入力します。
入力後に、echo $シェル変数名で格納された値の確認を行えます。

シェル変数を定義
[test_01@localhost ~]$ name="tanaka"
[test_01@localhost ~]$ echo $name
tanaka

また、setコマンドをオプション無しで実行する事でシェル変数の一覧を表示出来ます。
先程定義したnameを確認します。下記が実行結果となります。

シェル変数を確認
[test_01@localhost ~]$ set | grep "name"
name=tanaka

シェル変数を削除したい場合はunsetコマンドを実行します。
空白等を代入しても、削除されるわけではございません。変数自体は残ります。
※_=name と出力されておりますが、これは$_に直前のコマンドの引数が格納されているだけです。

シェル変数を削除
[test_01@localhost ~]$ unset name
[test_01@localhost ~]$ set | grep "name"
_=name

[test_01@localhost ~]$ name="tanaka"
[test_01@localhost ~]$ name=""
[test_01@localhost ~]$ set | grep "name"
name=

環境変数を定義する

環境変数を定義するには、exportコマンドを使用します。
また、環境変数の一覧を表示したい場合はenvコマンドprintenvコマンドを使用する事で確認出来ます。

環境変数を定義
[test_01@localhost ~]$ export name="tanaka"
[test_01@localhost ~]$ env | grep "tanaka"
name=tanaka

環境変数は子プロセスに引き継がれます。例として、シェルスクリプト内でechoコマンドを実行してみます。
下記に実行結果を載せています。

[test_01@localhost ~]$ cat test.sh
#!/bin/bash

echo $name
[test_01@localhost ~]$ ./test.sh
tanaka

シェル変数の場合は子プロセスに引き継がれないので、上記のような結果が得られません。

[test_01@localhost ~]$ unset name
[test_01@localhost ~]$ name="satou"
[test_01@localhost ~]$ ./test.sh

環境変数を削除したい場合は、export -nで削除出来ます。

環境変数を削除
[test_01@localhost ~]$ export -n name
[test_01@localhost ~]$ env | grep "name"
[test_01@localhost ~]$ set | grep "name"
name=satou
1
0
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
1
0