如何在Linux中设置环境变量

时间:2020-02-23 14:40:27  来源:igfitidea点击:

想知道如何在Linux中设置环境变量?这正是我们在本教程中将要做的。
操作系统利用环境变量来定义运行时环境的系统属性。

通过本教程,我们将帮助您了解环境变量的工作方式。
此外,我们将看到如何在Linux中设置环境变量或者如何根据需要重置现有的环境变量。

了解环境变量

当我们通过shell在服务器上启动会话时,它必须为我们创建一个环境。
这是我们通过shell与服务器交互所必须执行的步骤。

环境变量是特殊变量,可用于系统上的所有命令和进程。
这些变量具有以下格式。

ENVAR=value
ENVAR="Another value"
ENVAR=value_1:value_2

  • 所有变量名称均区分大小写。
    按照约定,我们为所有环境变量提供大写名称。

  • 在为变量赋值时,请确保赋值运算符(=)周围没有空格。

  • 如果需要为单个环境变量分配多个值,则可以使用冒号(:)分隔不同的值。

列出Linux中的现有环境变量

如果要查看当前会话的环境变量,请使用以下命令。

printenv

Linux系统中的打印环境变量

如上面的屏幕截图所示,此命令将打印当前shell会话的所有变量。
如果我们想要带有环境变量的shell变量列表,请使用此命令。

set

这将返回一个类似的输出,显示当前shell会话的shell变量。

以下是一些环境变量及其重要性的示例。

Type of VariableSignificance
SHELLThe shell which interprets all the commands entered by the user. Usually, this will be set to bash by default. But users can change it as per their to suit their needs.
USERThe username of the user currently logged on to the system.
LANGThe language and localization settings for the system currently in place, which includes character encoding.
TERMThe type of terminal which needs to be emulated when the shell is running. While this isn’t something you would need to usually worry about, there can be instances when your operating needs might require emulating a specific hardware terminal.
HOMEThe home directory for the user currently logged on to the system.
PATHThe list of directories in which our system will check when a command is entered by the user. This search of directories is done to find the executable files associated with the command.
PWDThe current directory which the user is working with.

如何在Linux中设置环境变量?

既然我们知道什么是环境变量,现在该学习如何在Linux中设置环境变量了。

1.创建一个shell变量并分配一个值

当我们需要创建一个新的环境变量时,我们首先需要创建一个变量并将其初始化。
对于本教程,我们将使用以下内容。

TESTVAR="This is a test variable"
echo $TESTVAR

我们已经使用echo命令来显示变量并确认其存在。

在Shell中设置变量

现在,如果使用如下所示的变量名称运行printenv命令,将不会获得任何输出,因为该变量当前是一个shell变量。

printenv TESTVAR

上面的命令不会提供任何输出,因为TESTVAR还不是环境变量。

2.导出以将其转换为环境变量

让我们使用export命令将其设置为环境变量,然后再次使用printenv命令。

export TESTVAR
printenv TESTVAR

在Linux中设置环境变量

如您在上面看到的,我们得到TESTVAR存储的值。
这是因为通过使用export命令,我们将TESTVAR设置为环境变量。

3.替代方案–结合两个步骤

要在Linux中设置环境变量时,有一种更常用的方法。
我们可以使用以下行来同时声明和导出变量。

export NEWTESTVAR="This is a new test variable"
printenv NEWTESTVAR

Linux 1中的一个行集环境变量

现在,当我们对新变量使用printenv命令时,我们将看到它立即显示环境变量。

如何在Linux中删除环境变量

现在我们知道了如何在Linux中设置环境变量,我们需要学习如何删除它们。
一旦我们不用创建的环境变量,建议将其删除。

这样可以确保不会意外调用环境变量。

1.使用导出命令

export -n TESTVAR
printenv TESTVAR

现在,如果尝试使用printenv命令获取TESTVAR的值,则不会获得任何输出。

这确认TESTVAR不再是环境变量。

2.使用unset命令

另外,我们可以使用unset命令。
使用它会完全删除该变量,因此它既不是环境变量也不是shell变量。

可以按照以下步骤完成。

unset TESTVAR

请注意,即使使用echo命令,也不会返回任何内容。
因此,我们知道该变量未设置。