【问题标题】:Set Environment Variable from shell script从 shell 脚本设置环境变量
【发布时间】:2016-06-01 09:23:48
【问题描述】:

我有一个像

这样的环境变量
ABC_XYZ=false

当我echo $ABC_XYZ 它给了我false 现在我在执行这些步骤的脚本中

>echo $ABC_XYZ 
false
>ABC_XYZ=true
>echo $ABC_XYZ
true

现在退出脚本后 echo $ABC_XYZ 再次给我false 我可以通过任何方式从脚本内部将值设置为 true。

提前致谢。

【问题讨论】:

    标签: bash shell unix


    【解决方案1】:

    您必须使用 source 在 shell 的当前上下文中运行脚本。

    假设你的脚本在你的当前目录中:

    $ source ./script_filename
    

    $ . ./script_filename
    

    引用help source

    source: 源文件名 [参数] 从当前 shell 中的文件执行命令。

    Read and execute commands from FILENAME in the current shell.  The
    entries in $PATH are used to find the directory containing FILENAME.
    If any ARGUMENTS are supplied, they become the positional parameters
    when FILENAME is executed.
    

    要使该变量在随后派生的子进程(shell 或任何其他进程)中可用,您需要在脚本中像这样导出环境变量:

    export ABC_XYZ
    

    【讨论】:

    • 添加源 ~/.bash_profile 并导出 ABC_XYZ 仍然没有成功
    • source script 必须写在命令行而不是脚本内
    【解决方案2】:

    尝试运行以下脚本文件:

    source ./export.bash
    

    【讨论】:

    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-03
    相关资源
    最近更新 更多