1

I have a string that contains a use of some variable, and I'd like to substitute that variable's value into the string. Right now the best I have is

#!/bin/bash

foo='$name; echo bar'
name="The    name"
expanded="$(eval echo "$foo")"
echo "$expanded"

Which has some obvious defects: it prints

The name
bar

while I'd like it to print

The    name; echo bar
3
  • 2
    sounds like a xy problem to me. what on earth are you trying to do? Commented Apr 1, 2015 at 16:18
  • I second huStmphHrrr's sentiment Commented Apr 1, 2015 at 16:26
  • @HuStmpHrrr You're right of course, but I am more curious about this than a solution to my actual problem which I have already solved a different way. Commented Apr 1, 2015 at 16:29

3 Answers 3

1

Instead of eval you can do bash's regex matching with bash's string replacement:

foo='$name; echo bar'
name="The    name"
[[ "$foo" =~ \$([[:alnum:]]+) ]] && s="${!BASH_REMATCH[1]}" &&
  expanded="${foo/\$${BASH_REMATCH[1]}/$s}"

echo "$expanded"
The    name; echo bar
Sign up to request clarification or add additional context in comments.

2 Comments

I'd like to do it for all variables that are currently defined, and support all of bash's syntax like ${name:-default} etc
ok check my updated answer for a generic solution. If there are multiple variable to be replaced then above snippet can also be run using a while loop.
1

Not exactly sure what you are trying to do but this works and you do not have (nor probably want) to use eval:

 name="The    name"
 foo="$name; echo bar"
 echo "$foo

prints

The    name; echo bar

1 Comment

In my case foo is a command line parameter, so I have no chance to define it after name.
0

You can do it like this:

#!/bin/bash

name="The    '     \" name"
foo="$name; echo bar"
expanded=$(eval 'echo "$foo"')
echo "$expanded"

Output:

The    '     " name; echo bar

3 Comments

It should be The name; echo bar though (4 spaces). EDIT: spaces got collapsed by the comment system, they go between The and name.
Thanks! Doesn't work if name contains ' though.
hmm, ok, another update.. name can contain both ' and " , and preserve all the spaces..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.