0

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?

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
Luis Andrés García
  • 5,852
  • 10
  • 43
  • 57
  • 2
    The standard solution to this is `eval`, but the standard solution also comes with the caveat that using `eval` opens up all kinds of security implications and code maintainability hassles. If you can, rethink your solution so it doesn't require `eval`. See e.g. http://stackoverflow.com/questions/6818948/nested-shell-variables-without-using-eval for a discussion. – tripleee Oct 01 '12 at 15:18
  • possible duplicate of [how to use a variable's value as other variable's name in bash](http://stackoverflow.com/questions/9714902/how-to-use-a-variables-value-as-other-variables-name-in-bash) – tripleee Oct 01 '12 at 15:20

3 Answers3

1

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 ...
ruakh
  • 175,680
  • 26
  • 273
  • 307
1

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.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

try this

cp myOtherFile `echo $a`
amphibient
  • 29,770
  • 54
  • 146
  • 240