【问题标题】:exporting variables which are variable values in shell导出作为 shell 中的变量值的变量
【发布时间】:2013-05-06 08:56:01
【问题描述】:

当我尝试这样做时......

$ export my_path='/my/path\ with\ spaces/file'
$ echo $my_path`
/my/path\ with\ spaces/file

有效。

但我想这样做..

$ echo $my_variable
my_path='/my/path\ with\ spaces/file'
$ export $my_variable
-bash: export: `with\': not a valid identifier
-bash: export: `spaces/file'': not a valid identifier

这是我得到的错误。 有没有办法处理要导出的变量的值.. [[ 注意:如果路径没有空格,它可以完美地工作!! ]]

【问题讨论】:

    标签: linux bash shell variables export


    【解决方案1】:

    不要使用$。否则,shell 会先扩展变量的值,然后再将其传递给export。以下将起作用:

    export my_variable
    

    在 cmets 中,它指出您不想将变量赋值本身存储为变量,然后将其传递给export。举个例子:

    var='foo=bar'
    export "$var"
    
    # check if it succeeded 
    export | grep foo # output: declare -x foo="bar"
    

    【讨论】:

    • 这是有效的,因为export 将扩展其参数的值。当您说export $foo 时,foo 将在传递给export 之前进行扩展,如果foo 包含空格,export 会认为它给出了几个作为shell 变量名称的参数。
    • 实际上,我的最终目标是导出“my_path”变量。不是“my_variable”本身。
    • 这样的? :$var='$foo=bar'; export "$var"
    • 不工作的人.. :( bash: export: '$foo=bar': not a valid identifier
    • var='foo=bar';导出“$var”
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2011-12-28
    • 2013-07-11
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多