I'd like to somehow spit out a file (which has env variable references) and substitute the actual values. This is what I've tried, but as you can see it's not working. Any ideas?

-bash-3.00$ cat vars_file 
${MY_VAR}
-bash-3.00$ export MY_VAR=MY_VALUE; cat ./vars_file | xargs echo
${MY_VAR}
link|improve this question

80% accept rate
feedback

2 Answers

up vote 1 down vote accepted
while read line; do eval echo $line; done < vars_file

http://www.issociate.de/board/post/281806/sed_replace_by_enviroment_var_content.html

link|improve this answer
any idea how to do this when there's a paren in the file? -bash: syntax error near unexpected token `(' – andersonbd1 Jan 20 '11 at 17:51
@andersonbd1: I suppose you could replace the parentheses with sed and replace them back later. Otherwise, you might want to consider to remove the accept mark from my answer to get a better awk solution, as the above questions mentions that you can't read the effect with sed. – Tom Wijsman Jan 20 '11 at 18:09
1  
I guess sed is my best bet. It ain't pretty but it'll work. Thanks TomWij – andersonbd1 Jan 20 '11 at 18:24
You might want to quote that variable: echo "$line". @andersonbd1: what is the context of the parentheses? – Dennis Williamson Jan 20 '11 at 19:06
1  
Oops, sorry, I forgot to say that you should use read -r, too. – Dennis Williamson Jan 20 '11 at 19:14
show 1 more comment
feedback

As described in the same thread at http://www.issociate.de/board/post/281806/sed_replace_by_enviroment_var_content.html, the "proper" solution would be as follows:

awk '{while(match($0,"[$]{[^}]*}")) {var=substr($0,RSTART+2,RLENGTH -3);gsub("[$]{"var"}",ENVIRON[var])}}1' < input.txt > output.txt

eval approach is fine, but tends to fail on XML files for instance.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.