linux bash 变量_如何在Linux上的Bash中设置环境变量

linux bash 变量_如何在Linux上的Bash中设置环境变量_第1张图片

linux bash 变量

linux bash 变量_如何在Linux上的Bash中设置环境变量_第2张图片 fatmawati achmad zaenuri/Shutterstock Fatmawati achmad zaenuri / Shutterstock

There’s more than one type of environment variable on Linux. Learn how to see them, create them for local and remote logins, and make them survive reboots.

Linux上有多种类型的环境变量。 了解如何查看它们,为本地和远程登录创建它们,并使它们在重启后不受影响。

环境变量如何工作 (How Environment Variables Work)

When you launch a terminal window and the shell inside it, a collection of variables is referenced to ensure the shell is configured correctly. These variables also ensure that any information to which the terminal window and shell might need to refer is available. Collectively, these variables hold settings that define the environment you find inside your terminal window, right down to the look of the command prompt. So, naturally, they’re referred to as environment variables.

启动终端窗口并在其中运行外壳程序时 ,将引用变量集合以确保正确配置外壳程序。 这些变量还确保可以使用终端窗口和外壳程序可能需要参考的任何信息。 这些变量共同保存用于定义您在终端窗口中找到的环境的设置,这些设置一直到命令提示符的外观。 因此,自然地,它们被称为环境变量。

Some environment variables are system-wide, or global. Others are session-wide and can only be seen by you. Others can’t reference your session environment variables. There’s a third set of environment variables defined within the shell. Your locale, time zone, and keyboard settings, the set of directories searched when the shell tries to find a command, and your default editor, are all stored in shell environment variables.

一些环境变量是系统范围的或全局的。 其他人则在整个会话范围内,只有您自己才能看到。 其他人则无法引用您的会话环境变量。 在外壳程序中定义了第三组环境变量。 您的语言环境,时区和键盘设置,shell尝试查找命令时搜索的目录集以及默认编辑器都存储在shell环境变量中。

We’re going to show you how to see the environment variables that exist on your system, and we’ll describe how to create your own. We’ll also show you how to make them available to child processes and to be persistent across reboots.

我们将向您展示如何查看系统中存在的环境变量,并描述如何创建自己的环境变量。 我们还将向您展示如何使它们可用于子进程以及如何在重新启动后保持持久性。

环境与继承 (Environments and Inheritance)

When a shell starts, it goes through an initialization phase. It’s at this point that it reads the environment variables that define the environment of the shell.

当shell启动时,它将经历初始化阶段。 至此,它读取定义外壳环境的环境变量。

When a program or command is launched from that shell—known as a child process—it inherits the environment of the parent process—but watch out! As we’ll see, you can create variables that don’t get added to your environment, so they won’t be inherited by a child process.

当从该外壳启动程序或命令时(称为子进程),它将继承父进程的环境,但要当心! 正如我们将看到的,您可以创建不会添加到您的环境中的变量,这样子进程就不会继承它们。

If the child process is a shell, that shell will initialize from its own, fresh, set of variables. So, if you alter the command prompt in the current shell, and then launch a child shell, the child shell won’t inherit the modified command prompt of the parent.

如果子进程是一个外壳程序,则该外壳程序将从其自己的新鲜变量集进行初始化。 因此,如果您更改当前外壳程序中的命令提示符,然后启动子外壳程序,则该子外壳程序将不会继承父级的修改后的命令提示符。

全局环境变量 (Global Environment Variables)

By convention, environment variables are given uppercase names. Here are some of the global environment variables, and what the values they contain represent:

按照约定,环境变量被赋予大写名称。 以下是一些全局环境变量以及它们包含的值表示:

  • SHELL: The name of the shell that will launch when you open a terminal window. On most Linux distributions, this will be bash unless you changed it from the default.

    外壳:打开终端窗口时将启动的外壳的名称。 在大多数Linux发行版中,除非您将默认设置更改为bash,否则它将为bash 。

  • TERM: Terminal windows are actually emulations of a hardware terminal. This holds the type of hardware terminal that will be emulated.

    术语:终端窗口实际上是硬件终端的仿真。 这保存了将要仿真的硬件终端的类型。

  • USER: The username of the current person using the system.

    USER:使用系统的当前用户的用户名。

  • PWD: The path to the current working directory.

    PWD:当前工作目录的路径。

  • OLDPWD: The directory you were in prior to moving to the current working directory.

    OLDPWD:移至当前工作目录之前的目录。

  • LS_COLORS: The list of color codes used by the ls highlight different file types.

    LS_COLORS: ls使用的颜色代码列表突出显示了不同的文件类型 。

  • MAIL: If the mailsystem has been set up on your Linux computer (by default, it isn’t), this will hold the path to the current user’s mailbox.

    邮件:如果您Linux计算机上已设置了mail系统(默认情况下未设置),它将保留当前用户邮箱的路径 。

  • PATH: A list of directories that the shell will search through to find command executables.

    PATH:外壳程序将搜索以查找命令可执行文件的目录列表。

  • LANG: The language, localization, and character encoding settings.

    LANG:语言,本地化和字符编码设置。

  • HOME: The home directory of the current user.

    HOME:当前用户的主目录。

  • _: The underscore (_) environment variable holds the last command that was typed.

    _:下划线( _ )环境变量保存最后键入的命令。

We can see what some of these are set to using nothing more sophisticated than echo, which will write the values to the terminal window. To see the value held by an environment variable, you need to add a dollar sign ($) to the start of its name.

我们可以看到其中一些设置为使用echo复杂的功能,它将echo 显值写入终端窗口 。 要查看环境变量持有的 ,您需要在其名称的开头添加一个美元符号( $ )。

A nice touch is that you can use tab completion to fill in the environment variable name for you. Type a few letters of the name and hit Tab. The name of the variable is completed by the shell. If that doesn’t happen, you’ll need to type a few more letters to distinguish the environment variable from other commands with names that start with those same letters:

一个不错的感觉是,您可以使用制表符补全为您填写环境变量名称。 输入名称的几个字母,然后按Tab。 变量的名称由外壳程序完成。 如果那没有发生,您将需要再输入几个字母以将环境变量与其他以相同字母开头的名称的命令区分开来:

echo $SHELL
echo $LANG
echo $HOME
echo $PWD
linux bash 变量_如何在Linux上的Bash中设置环境变量_第3张图片

To create your own global environment variables, add them to the /etc/environment file. You’ll need to use sudo to edit this file:

要创建自己的全局环境变量,请将它们添加到/etc/environment文件中。 您需要使用sudo来编辑此文件:

sudo gedit /etc/environment
sudo gedit /etc/environment in a terminal window

To add an environment variable, type its name, an equal sign (=), and the value you want the environment variable to hold. Don’t space before or after the equal sign (=). The name of the environment variable can contain letters, an underscore (_), or numbers. However, the first character of a name cannot be a number.

要添加环境变量,请键入其名称,等号( = )和要环境变量保存的值。 在等号( = )之前或之后不要空格。 环境变量的名称可以包含字母,下划线( _ )或数字。 但是,名称的第一个字符不能是数字。

If there are spaces in the value, be sure you enclose the entire value in quotation marks (").

如果值中有空格,请确保将整个值括在引号( " )中。

The /etc/environment file opened in an editor and a new environment variable being added.

Save the file, and then log out and back in again. Use echo to test that a new variable exists and holds the value you set:

保存文件,然后注销并再次登录。 使用echo测试新变量是否存在并保存您设置的值:

echo $WEBSITE
echo $WEBSITE in a terminal window.

Because it’s a global environmental variable, and available to everyone, user mary can reference the environment variable when she next logs in:

因为这是一个全局环境变量,并且所有人都可以使用,所以用户mary在下次登录时可以引用该环境变量:

echo $WEBSITE
echo $WEBSITE in a terminal window.

To see all the environment variables at once, type printenv. There’s a lot of output, so it makes sense to pipe it through sort, and then into less:

要一次查看所有环境变量 ,请输入printenv 。 有很多输出,因此将它通过sort传递到less是有意义的:

printenv | sort | less
printenv | sort | less in a terminal window.

The sorted list of environment variables is displayed for us in less.

环境变量的排序列表在less为我们显示。

linux bash 变量_如何在Linux上的Bash中设置环境变量_第4张图片

We can pipe the output through grep to look for environment variables related to a particular topic.

我们可以通过grep传递输出,以查找与特定主题相关的环境变量。

printenv | grep GNOME
linux bash 变量_如何在Linux上的Bash中设置环境变量_第5张图片

Shell环境变量 (Shell Environment Variables)

These are some of the shell environment variables used in bash to dictate or record its behavior and functionality. Some of the values are updated as you use the terminal. For example, the COLUMNS environment variable will be updated to reflect changes you might make to the width of the terminal window:

这些是bash用于指示或记录其行为和功能的一些shell环境变量。 使用终端时,某些值会更新。 例如,将更新COLUMNS环境变量以反映您可能对终端窗口的宽度所做的更改:

  • BASHOPTS: The command-line options that were used when bash was launched.

    BASHOPTS:启动bash时使用的命令行选项。

  • BASH_VERSION: The bash version number as a string of words and numbers.

    BASH_VERSION: bash版本号,由单词和数字组成的字符串。

  • BASH_VERSINFO: The bash version as a digit.

    BASH_VERSINFO: bash版本为数字。

  • COLUMNS: The current width of the terminal window.

    列:终端窗口的当前宽度。

  • DIRSTACK: The directories that have been added to the directory stack by the pushd command.

    DIRSTACK:已的目录添加到目录栈由pushd命令。

  • HISTFILESIZE: Maximum number of lines permitted in the  history file.

    HISTFILESIZE: history文件中允许的最大行数。

  • HISTSIZE: Number of lines of history allowed in memory.

    HISTSIZE:内存中允许的history行数。

  • HOSTNAME: The hostname of the computer.

    HOSTNAME:计算机的主机名。

  • IFS: The Internal Field Separator used to separate input on the command line. By default, this is a space.

    IFS: 内部字段分隔符,用于分隔命令行上的输入。 默认情况下,这是一个空格。

  • PS1: The PS1 environment variable holds the definition for the primary, default, and command prompt. A set of tokens called escape sequences can be included in the definition of your command prompt. They represent such things as the host- and username, the current working directory, and the time.

    PS1: PS1环境变量包含主,默认和命令提示符的定义。 一组称为转义序列的标记可以包含在命令提示符的定义中。 它们代表诸如主机名和用户名,当前工作目录和时间之类的东西。

  • PS2: When a command spans more than one line and more input is expected, the secondary command prompt is shown. The PS2 environment variable holds the definition of this secondary prompt, which, by default, is the greater than sign (>).

    PS2:当命令跨越多行并且需要更多输入时,将显示辅助命令提示符。 PS2环境变量保存此辅助提示的定义,默认情况下,该提示大于号( > )。

  • SHELLOPTS: Shell options you can set using the set option.

    SHELLOPTS:您可以使用set选项设置的Shell选项。

  • UID: The User Identifier of the current user.

    UID:当前用户的用户标识 。

Let’s check a few of these shell variables:

让我们检查以下一些shell变量:

echo $BASH_VERSION
echo $HOSTNAME
echo $COLUMNS
echo $HISTFILESIZE
echo $UID
linux bash 变量_如何在Linux上的Bash中设置环境变量_第6张图片

For the sake of completeness, here are the tokens you can use in the command prompt definitions:

为了完整起见,以下是您可以在命令提示符定义中使用的标记:

  • \t: The current time, formatted as HH:MM:SS.

    \ t:当前时间,格式为HH:MM:SS。

  • \d: The current date, expressed as weekday, month, date.

    \ d:当前日期,表示为工作日,月份,日期。

  • \n: A new-line character.

    \ n:换行符。

  • \s: The name of your shell.

    \ s:您的外壳的名称。

  • \W: The name of your current working directory.

    \ W:您当前工作目录的名称。

  • \w: The path to your current working directory.

    \ w:当前工作目录的路径。

  • \u: The username of the person who’s logged in.

    \ u:登录人员的用户名。

  • \h: The hostname of the computer.

    \ h:计算机的主机名。

  • \#: Each command within a shell is numbered. This allows you to see the number of the command in your command prompt. This is not the same as the number the command will have in the history list.

    \#: shell中的每个命令都有编号。 这使您可以在命令提示符下查看命令的编号。 这与命令在history列表中的编号不同。

  • \$: Sets the final character of the prompt to a dollar sign ($) for a regular user, and a hash symbol (#) for the root user. This works by checking the UID of the user. If it’s zero, the user is root.

    \ $:对于普通用户,将提示的最终字符设置为美元符号( $ ),对于root用户,将其设置为井号( # )。 这通过检查用户的UID起作用。 如果为零,则用户为root。

You’ll find the definition of your PS1 environment variable in your .bashrc file.

您可以在.bashrc文件中找到PS1环境变量的定义。

创建会话环境变量 (Creating Session Environment Variables)

To create environment variables for your own use, add them to the bottom of your .bashrc file. If you want to have the environment variables available to remote sessions, such as SSH connections, you’ll need to add them to your .bash_profile file, as well.

要创建自己使用的环境变量,请将其添加到.bashrc文件的底部。 如果要使环境变量可用于远程会话(例如SSH连接),则还需要将它们添加到.bash_profile文件中。

The format of the environment variable definition is the same for both files. To add a definition to your .bash_profile file, type this in your home directory:

这两个文件的环境变量定义格式相同。 要将定义添加到.bash_profile文件,请在主目录中键入以下内容:

gedit .bashrc
.bashrc file lodaed into an editor and a new environment variable added as the last line in the file.

We’ve added an environment variable called INHERITED_VAR. Note the word “export” at the start of the line.

我们添加了一个名为INHERITED_VAR的环境变量。 请注意该行开头的单词“ export”。

linux bash 变量_如何在Linux上的Bash中设置环境变量_第7张图片

Save and close your file after you finish editing. You could log out and back in again, or you can cause the shell to re-read the .bash_profile file using the dot command (.) like this:

完成编辑后,保存并关闭文件。 您可以注销然后再次登录,也可以使外壳使用点命令( . )重新读取.bash_profile文件,如下所示:

. .bashrc
. .bashrc in a terminal window.

Now, let’s create an environment variable on the command line:

现在,让我们在命令行上创建一个环境变量:

LOCAL_VAR="This session only"
LOCAL_VAL=

If we use echo, we can see that both environment variables are accessible to us:

如果我们使用echo ,我们可以看到我们可以访问两个环境变量:

echo $LOCAL_VAR
echo $INHERITED_VAR
linux bash 变量_如何在Linux上的Bash中设置环境变量_第8张图片

You’ll notice the definition of the INHERITED_VAR environment variable had the word “export” at the start of the line. This means the environment variable will be inherited by child processes of the current shell. If we launch another one using the bash command, we can check the two variables again, from inside the child shell:

您会注意到INHERITED_VAR环境变量的定义在该行的开头INHERITED_VAR单词“ export”。 这意味着环境变量将被当前shell的子进程继承。 如果我们使用bash命令启动另一个,则可以从子外壳内部再次检查两个变量:

bash
echo $LOCAL_VAR
echo $INHERITED_VAR
linux bash 变量_如何在Linux上的Bash中设置环境变量_第9张图片

As you can see, the INHERITED_VAR is accessible in the child shell, but LOCAL_VAR is not.  We simply get a blank line.

如您所见,在子外壳程序中可以访问INHERITED_VAR ,但不能访问LOCAL_VAR 。 我们只是得到一个空白行。

Although “export” adds the environment variable part to the environment that child processes inherit, INHERITED_VAR is not a global environment variable. For example, user mary cannot reference it:

尽管“导出”将环境变量部分添加到子进程继承的环境中,但是INHERITED_VAR不是全局环境变量。 例如,用户mary无法引用它:

echo $INHERITED_VAR
echo $INHERITED_VAR in a terminal window.

To close our child bash session, we use exit:

要关闭子bash会话,我们使用exit

exit

Inherited environments affect scripts, too. Here’s a simple script that writes the values of our three environment variables to the terminal window:

继承的环境也会影响脚本。 这是一个简单的脚本,它将我们三个环境变量的值写入终端窗口:

#!/bin/bash

echo "WEBSITE" $WEBSITE
echo "LOCAL_VAR" $LOCAL_VAR
echo "INHERITED_VAR" $INHERITED_VAR

This was saved to a file called envtest.sh, and then made executable with the following:

将该文件保存到名为envtest.sh的文件中,然后使用以下命令使其可执行:

chmod +x envtest.sh

When we run the script, it can access two out of three environment variables:

运行脚本时,它可以访问三个环境变量中的两个:

./envtest.sh
linux bash 变量_如何在Linux上的Bash中设置环境变量_第10张图片

The script can see the WEBSITE global environment variable and the INHERITED_VAR exported environment variable. It cannot access LOCAL_VAR, even though the script is running in the same shell where the variable was created.

该脚本可以查看WEBSITE全局环境变量和INHERITED_VAR导出的环境变量。 即使脚本在创建变量的同一shell中运行,它也无法访问LOCAL_VAR

If we need to, we can export an environment variable from the command line. We’ll do that to our LOCAL_VAR, and then run the script again:

如果需要,我们可以从命令行导出环境变量。 我们将对LOCAL_VAR执行此LOCAL_VAR ,然后再次运行脚本:

export LOCAL_VAR
./envtest.sh
linux bash 变量_如何在Linux上的Bash中设置环境变量_第11张图片

The environment variable has been added to the environment of the current shell, and so it appears in the environment that is inherited by the script. The script can reference that environment variable, too.

环境变量已添加到当前外壳程序的环境中,因此它出现在脚本继承的环境中。 该脚本也可以引用该环境变量。

远程连接 (Remote Connections)

Global environment variables are accessible to remote login sessions, but if you want your locally defined environment variables available to you remotely, you must add them to your .bash_profile file. You can set the same environment variable in the .bashrc and .bash_profile files, with different values. This could be picked up by a script, say, to modify its behavior for people using the system locally or remotely.

全局环境变量可用于远程登录会话,但是如果您希望远程使用本地定义的环境变量,则必须将它们添加到.bash_profile文件中。 您可以在.bashrc.bash_profile文件中设置相同的环境变量,并使用不同的值。 例如,可以通过脚本进行选择,以便为本地或远程使用系统的人员修改其行为。

(At the risk of confusing matters, there’s also a .profile file. It can hold environment variable definitions, too. However, the .profile file is not read if the .bash_profile file is present. So, the safest thing to do—and the bash-compliant way—is to use the .bash_profile file.)

(存在混淆的风险,还有一个.profile文件。它也可以保存环境变量定义。但是,如果存在.bash_profile文件,则不会读取.profile文件。因此,最安全的做法是-并且bash兼容的方法-使用.bash_profile文件。)

To edit the .bash_profile file, we’ll use gedit again:

要编辑.bash_profile文件,我们将再次使用gedit

gedit .bash_profile
gedit .bash_profile in a terminal window.

We’re going to add the same environment variable with the same value we used before.

我们将使用相同的值添加相同的环境变量。

The .bash_profile file opened in an editor with a new environment variable being added.

Save your changes and close gedit.

保存更改并关闭gedit

On another computer, we’ll make an SSH connection to the test computer.

在另一台计算机上,我们将与测试计算机建立SSH 连接 。

ssh [email protected]
ssh dave@howtogeek.local in a terminal window.

Once we’re connected, we’ll run the script once more:

建立连接后,我们将再次运行脚本:

./envtest.sh
linux bash 变量_如何在Linux上的Bash中设置环境变量_第12张图片

The .bash_profile file has been read as part of the initialization of the remote login, and the INHERITED_VAR environment variable is accessible to us and the script.

.bash_profile文件已作为远程登录初始化的一部分被读取,并且我们和脚本均可访问INHERITED_VAR环境变量。

取消环境变量 (Unsetting an Environment Variable)

To unset an environment variable use the unset command. If we unset the global environment variable, WEBSITE, and the exported environment variable, INHERITED_VAR, they’ll no longer be available on the command line, nor in child processes:

要取消设置环境变量,请使用unset命令 。 如果我们取消设置全局环境变量WEBSITE和导出的环境变量INHERITED_VAR ,则它们将不再在命令行或子进程中可用:

unset WEBSITE
unset INHERITED_VAR
./envtest.sh
echo $WEBSITE
linux bash 变量_如何在Linux上的Bash中设置环境变量_第13张图片

A point to note is this only changes the availability of global environment variables for you in this session. Another person who’s logged in simultaneously will still be able to access his instance of that global environment variable. His instance was initialized and read from the /etc/environment file during his login process, and is independent of anyone else’s copy of the variable.

需要注意的一点是,这只会在此会话中更改全局环境变量的可用性。 同时登录的另一个人仍然可以访问该全局环境变量的实例。 他的实例在登录过程中已初始化并从/etc/environment文件中读取,并且独立于其他任何人的变量副本。

As an example, user mary can still access the WEBSITE environment variable and read its value, even though user dave has unset it in his session:

例如,用户mary仍然可以访问WEBSITE环境变量并读取其值,即使用户dave在其会话中未unset它:

echo $WEBSITE
echo %WEBSITE in a terminal window.

环境控制 (Environmental Control)

Environment variables can be used to let scripts and applications know how they should behave. They can be used to store settings or small amounts of data. For example, a script can populate an environment with a value that can be referenced by other scripts without having to write them to a file.

环境变量可用于让脚本和应用程序知道其行为。 它们可用于存储设置或少量数据。 例如,脚本可以使用其他脚本可以引用的值填充环境,而不必将其写入文件。

翻译自: https://www.howtogeek.com/668503/how-to-set-environment-variables-in-bash-on-linux/

linux bash 变量

你可能感兴趣的:(python,linux,java,shell,数据库)