bash 如何在bash中导出变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/307120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:32:09  来源:igfitidea点击:

How to export a variable in bash

linuxbashsysadmin

提问by mbrevoort

I need to set a system environment variable from a bash script that would be available outside of the current scope. So you would normally export environment variables like this:

我需要从 bash 脚本设置一个系统环境变量,该脚本在当前范围之外可用。所以你通常会像这样导出环境变量:

export MY_VAR=/opt/my_var

But I need the environment variable to be available at a system level though. Is this possible?

但是我需要环境变量在系统级别可用。这可能吗?

采纳答案by Jeremy Cantrell

This is the only way I know to do what you want:

这是我知道做你想做的唯一方法:

In foo.sh, you have:

在 foo.sh 中,您有:

#!/bin/bash
echo MYVAR=abc123

And when you want to get the value of the variable, you have to do the following:

而当你想要获取变量的值时,你必须执行以下操作:

$ eval "$(foo.sh)"  # assuming foo.sh is in your $PATH
$ echo $MYVAR #==> abc123

Depending on what you want to do, and how you want to do it, Douglas Leeder's suggestion about using source could be used, but it will source the whole file, functions and all. Using eval, only the stuff that gets echoed will be evaluated.

根据您想要做什么以及您想要如何做,可以使用 Douglas Leeder 关于使用源代码的建议,但它将提供整个文件、函数和所有内容的源代码。使用 eval,只会评估得到回显的内容。

回答by Douglas Leeder

Not really - once you're running in a subprocess you can't affect your parent.

不是真的 - 一旦你在子进程中运行,你就不能影响你的父进程。

There two possibilities:

有两种可能:

1) Source the script rather than run it (see source .):

1) 获取脚本而不是运行它(参见source .):

    source {script}

2) Have the script output the export commands, and eval that:

2)让脚本输出导出命令,并评估:

    eval `bash {script}`
OR:
    eval "$(bash script.sh)"

EDIT: Corrected the second option to be eval rather than source. Opps.

编辑:将第二个选项更正为 eval 而不是源。奥普斯。

回答by nicerobot

Set the variable in /etc/profile (create the file if needed). That will essentially make the variable available to every bash process.

在 /etc/profile 中设置变量(如果需要,创建文件)。这基本上将使该变量可用于每个 bash 进程。

回答by j0hnn0

Set the variable in /etc/profile (create the file if needed). That will essentially make the variable available to every bash process.

在 /etc/profile 中设置变量(如果需要,创建文件)。这基本上将使该变量可用于每个 bash 进程。

...to every NEW bash process...

...对每个新的 bash 进程...