简体   繁体   中英

Linux script: Reinterpret environment variable

I am creating a Bash script which reads some other environment variables:

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:

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" : 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?

It sounds like you want $HOME/myfile to support Bash notations, such as parameter-expansion. I think the best way to do that is to modify $HOME/myfile to be, in essence, a Bash script:

export a=$b/c/d/e

and use the source builtin to run it as part of the current Bash script:

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

You need eval to do this :

$ 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

And a safer approach is to use declare instead of eval :

declare "$x=another_value"

Thanks to chepner 2 for the latest.

尝试这个

cp myOtherFile `echo $a`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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