【问题标题】:shell script unable to set environment variable with the grepped valueshell 脚本无法使用 grepped 值设置环境变量
【发布时间】:2015-04-13 20:35:30
【问题描述】:

在 shell 脚本中,我想从日志文件中 grep 一个值并设置为一个环境的值。在日志文件中,有这样一行:

SOME_PATH=/some/specific/path

在我的 shell 脚本中,我 grep 了 SOME_PATH 关键字,我得到了上面的行并将其拆分为 =,但我现在可以设置环境变量:

line=`grep "SOME_PATH" /path/to/the/log.log`
path=${line##*=} 
export SOME_PATH="$path"  #I cannot change the environment variable with this line.

如果我只有下面这样的脚本,环境变量会发生变化。

export SOME_PATH=/some/specific/path

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    在由exported var 生成的 shell(脚本)或在另一个带有 sourced 脚本和 export 语句的脚本中生成的进程中可用的导出变量。

    第一种方式:

    $ cat exp.sh
    #!/bin/bash
    
    export MYVAR="hi there"
    bash
    # or bash -c "echo here: $MYVAR"
    

    第二种方式:

    $ cat exp.sh
    #!/bin/bash
    
    export MYVAR="hi there"
    
    $ cat imp.sh
    #!/bin/bash
    
    . exp.sh
    
    echo $MYVAR
    

    这是另一种解释:advanced bash scripting guide

    【讨论】:

    • 嗨,我sourced脚本在运行时,在你的回答中,我得到了cat: exp.sh: No such file or directory的错误
    • 那是因为你还没有创建它;)
    猜你喜欢
    • 1970-01-01
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2015-03-02
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多