版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014471752/article/details/84566830
Linux环境变量之export详解
linux中经常会配置环境变量的值,其中在配置有些环境变量的值之前会加export, 有些则不会,尤其在.bashrc .profile /etc/bash.bashrc中配置用户或者系统的环境变量时会产生一定的疑问。
归根结底,使用export与否,取决于希望该变量的作用域,使用export的话,则其作用域在当前shell启动的所有程序中,不使用则仅仅作用于当前shell,并不能作用于子进程中。
example_1:
非.bashrc .profile /etc/bash.bashrc中设置环境变量时:
user@pc:~$ VAL_TS='hello' #定义非export变量 VAL_TS
user@pc:~$ echo $VAL_TS #输出变量 VAL_TS 的值
#结果
hello
user@pc:~$ echo 'echo "val is :" $VAL_TS' > test.sh #添加脚本语句到 test.sh
user@pc:~$ ./test.sh #执行脚本 test.sh
#结果
val is : #解析不到VAL_TS变量的值
user@pc:~$ export EX_VAL_TS='world' #定义export变量 EX_VAL_TS
user@pc:~$ echo $EX_VAL_TS #输出变量 EX_VAL_TS
#结果
world
user@pc:~$ echo 'echo "export val is :" $EX_VAL_TS' >> test.sh #添加脚本语句到 test.sh
user@pc:~$ ./test.sh #执行脚本 test.sh
#结果
val is :
export val is : world #可以解析到变量EX_VAL_TS的值
example_2:
当在~/.bashrc中添加当前用户的环境变量时,非export变量的作用域仅为当前用户的所有交互式shell, 而不会作用域非交互式shell。
user@pc:~$ echo 'VAL_TS="hello, no export"' >> ~/.bashrc #添加非export变量赋值到.bashrc
user@pc:~$ source ~/.bashrc #使.bashrc生效
user@pc:~$ echo $VAL_TS #输出变量 VAL_TS 值
#结果
hello, no export
user@pc:~$ echo 'echo "val is :" $VAL_TS' > test.sh #添加脚本语句到脚本 test.sh
user@pc:~$ ./test.sh #执行脚本 test.sh
#结果
val is : #脚本中并没有变量值
user@pc:~$ echo 'export EX_VAL_TS="hello, export"' >> ~/.bashrc #添加export变量赋值
user@pc:~$ source ~/.bashrc #使.bashrc生效
user@pc:~$ echo $EX_VAL_TS #输出变量 EX_VAL_TS 值
#结果
hello, export
user@pc:~$ echo 'echo "export val is :$EX_VAL_TS' >> test.sh #添加脚本语句到脚本
user@pc:~$ ./test.sh #执行脚本 test.sh
#结果
export val is :hello, export #脚本中获取到了变量值
总结:
export决定了环境变量的作用范围,显式的export作用的都是交互式shell,而在非交互式shell中如果需要用到某个环境变量,则需要在其赋值时加前缀 export