Ramprasad R A
Ramprasad R A

Reputation: 51

Cant access the variable as variable stored in a file using bash

I have a bash script like

source ./testscript

while read line
do
      echo "$line"
done < "test.file"

where the testscript is like

VAR="hello"

the test.file is like

"$VAR" world!!!

I expect the output of my bash script to be

hello world!!!

but what i get is

"$VAR" world!!!

Is there any solution?

Upvotes: 1

Views: 58

Answers (2)

Adrian Fr&#252;hwirth
Adrian Fr&#252;hwirth

Reputation: 45566

You don't want to use eval. eval would allow arbitrary code to be embedded into your (text?) file which is certainly not what you want, especially if untrusted users have write access to said file.

If you don't need to expand arbitrarily named variables you can do something like the following, but there might be a better approach to the problem you are actually trying to solve.

$ cat t.sh
#!/bin/bash

VAR1=hello
VAR2='!!!'
FOO=test

expand_vars()
{
        local s=$*
        local var
        for var in VAR{1..9} FOO; do
                s=${s//%${var}%/${!var}}
        done
        echo "${s}"
}

while read line; do
        line=$(expand_vars "${line}")
        echo "${line}"
done <<__DATA__
%VAR1% world%VAR2%
This is a %FOO%
__DATA__

.

$ ./t.sh
hello world!!!
This is a test

Upvotes: 1

Oleg
Oleg

Reputation: 67

you can try

echo `eval "echo $line"`

instead of

echo "$line"

Upvotes: 1

Related Questions