当前位置: 首页>>技术问答>>正文


环境变量vs Shell变量,有什么区别?

, , ,

问题描述

有人告诉我:

BASH isn’t an environment variable, it’s a shell variable

有什么不同?

最佳解决方案

$BASH是一个局部变量,仅在当前(bash)shell中有效。

环境变量(如$SHELL)在系统范围内有效。在当前的Bash shell中,$BASH指向bash的执行路径,而$SHELL指向定义为default的shell(可能具有相同的值)。

有关环境变量的说明,请参阅Ubuntu帮助中的Environment Variables

次佳解决方案

环境变量是全局可用的,在程序和子程序中。 shell变量仅在当前shell中可用。要使shell变量可用作环境变量,请使用export VARNAME(不带美元$)。

澄清的例子:

$ SOME=VAR # define shell variable $SOME
$ echo $SOME
VAR
$ env | grep SOME # note: no output
$ export SOME # turn $SOME into an environment variable
$ env | grep SOME
SOME=VAR

另一种定义环境变量的方法:

$ export ANOTHER=VALUE
$ echo $ANOTHER
VALUE
$ env | grep ANOTHER
ANOTHER=VALUE

第三种解决方案

它们是有区别的。 Shell Variables and Environment Variables会更好地解释它,但这里有一段摘录:

If a change is made to a shell variable, it must be explicitly “exported” to the corresponding environment variable in order for any forked subprocesses to see the change. Recall that shell variables are local to the shell in which they were defined.

第四种方案

Shell变量:短期,仅适用于shell的当前实例,不适用于系统范围

环境变量:长期使用,有效系统范围,全球允许

按照惯例,Shell变量的名称为小写,而Envn。变量写为大写

参考资料

本文由Ubuntu问答整理, 博文地址: https://ubuntuqa.com/article/2203.html,未经允许,请勿转载。