alexandernst
alexandernst

Reputation: 15099

Expand bash var inside a string

I have this:

read -d '' foo <<-EOF
FOO "${filename}" BAR {\
\       FOO BAR FOO {BAR};\
\       FOO BAR FOO {BAR};\
};
EOF

filename="bar";

eval echo $foo;

And as you might already guessed, I'm trying to expand $filename inside $foo.

What am I doing wrong?

EDIT:

Error I'm getting:

./test.sh: eval: line 10: syntax error near unexpected token `}'
./test.sh: eval: line 10: `echo FOO "" BAR { FOO BAR FOO {BAR}; FOO BAR FOO {BAR};};'

Upvotes: 1

Views: 125

Answers (2)

hek2mgl
hek2mgl

Reputation: 157947

I don't think that it is possible (update: read the accepted answer ;) what you are trying to do. This is because the eval command requires that that $foo contains valid bash syntax.

I would use bash's string manipulation operators to replace $filename:

#!/bin/bash

read -d '' foo <<'EOF'
FOO "$filename" {
       FOO BAR FOO BAR;
       FOO BAR FOO BAR;
};
EOF

filename="bar";

echo "${foo/\$filename/$filename}"

filename="bar2";

echo "${foo/\$filename/$filename}"

Upvotes: 2

dogbane
dogbane

Reputation: 274532

You need to do the following:

  • quote the word EOF so that any variables in the heredoc are not expanded.
  • escape the semicolons
  • add the -r option to read so that it does not treat backslash as an escape character

Try this:

read -r -d '' foo <<-"EOF"
FOO "${filename}" BAR {\
\       FOO BAR FOO {BAR}\;\
\       FOO BAR FOO {BAR}\;\
}\;
EOF

filename="bar"

eval echo "$foo"

Output:

FOO bar BAR {  FOO BAR FOO {BAR};  FOO BAR FOO {BAR};};

Upvotes: 2

Related Questions