简体   繁体   English

Linux脚本:重新解释环境变量

[英]Linux script: Reinterpret environment variable

I am creating a Bash script which reads some other environment variables: 我正在创建一个Bash脚本,它读取一些其他环境变量:

echo "Exporting configuration variables..."
while IFS="=" read -r k v; do
    key=$k
    value=$v

    if [[ ${#key} > 0 && ${#value} > 0 ]]; then
        export $key=$value
    fi
done < $HOME/myfile

and have the variable: 并有变量:

$a=$b/c/d/e

and want to call $a as in: 并希望拨打$a如下所示:

cp myOtherFile $a

The result for the destination folder for the copy is "$b/c/d/e", and an error is shown: 副本的目标文件夹的结果是“$ b / c / d / e”,并显示错误:

"$b/c/d/e" : No such file or directory

because it is interpreted literally as a folder path. 因为它实际上被解释为文件夹路径。

Can this path be reinterpreted before being used in the cp command? cp命令中使用之前,是否可以重新解释此路径?

It sounds like you want $HOME/myfile to support Bash notations, such as parameter-expansion. 听起来你想要$HOME/myfile来支持Bash符号,比如参数扩展。 I think the best way to do that is to modify $HOME/myfile to be, in essence, a Bash script: 我认为最好的方法是修改$HOME/myfile ,实质上是一个Bash脚本:

export a=$b/c/d/e

and use the source builtin to run it as part of the current Bash script: 并使用内置的source将其作为当前Bash脚本的一部分运行:

source $HOME/myfile
... commands ...
cp myOtherFile "$a"
... commands ...

You need eval to do this : 你需要eval来做到这一点:

$ var=foo
$ x=var
$ eval $x=another_value
$ echo $var
another_value

I recommend you this doc before using eval : http://mywiki.wooledge.org/BashFAQ/048 在使用eval之前,我建议你使用这个文档: http//mywiki.wooledge.org/BashFAQ/048

And a safer approach is to use declare instead of eval : 更安全的方法是使用declare而不是eval

declare "$x=another_value"

Thanks to chepner 2 for the latest. 感谢最新的chepner 2。

尝试这个

cp myOtherFile `echo $a`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM