Skip to content

Instantly share code, notes, and snippets.

@janl
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janl/67ab4f9efd89ecec4030 to your computer and use it in GitHub Desktop.
Save janl/67ab4f9efd89ecec4030 to your computer and use it in GitHub Desktop.
string interpolation / variable substitution
#!/bin/sh -ex
# I have a variable that’s a string, that includes the expansion for another variable, albeit quited: `\${foo}`
# how can I get a string that is that original string, but with the variable expanded?
# no bashisms allowed, this needs to be stock-sh.
var1=foo
var2=\${var1}/bar
# insert magic here
eval var3=$var2
echo $var3 # prints `foo/bar
@tobie
Copy link

tobie commented Jun 24, 2015

Do you mean var2='\${var1}/bar' in line 8 or am I misunderstanding what you're doing completely?

@janl
Copy link
Author

janl commented Jun 24, 2015

@tobie yeah, did mean that, post the solution now

@tobie
Copy link

tobie commented Jun 24, 2015

:)

@tobie
Copy link

tobie commented Jun 24, 2015

eval echo `eval echo $var2`

@tobie
Copy link

tobie commented Jun 24, 2015

Think what you want is:

var1=foo;
varx=var1;
echo "${!varx}/bar";

But that's a bashism afaik. See: http://stackoverflow.com/a/11065196, in particular:

eval is not used very often. In some shells, the most common use is to obtain the value of a variable whose name is not known until runtime. In bash, this is not necessary thanks to the ${!VAR} syntax.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment