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?

Upvotes: 0

Views: 297

Answers (3)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185025

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.

Upvotes: 1

ruakh
ruakh

Reputation: 183270

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 ...

Upvotes: 1

amphibient
amphibient

Reputation: 31212

try this

cp myOtherFile `echo $a`

Upvotes: 0

Related Questions