Copy file and evaluate its internal variables

Hi

I have been trying to figure a way to copy a file, (a template), that has internal variables. Using the values as defined for those variables in another script.

So a file called x -

#! /bin/bash
D=aa.$X.bb

And file y

#! /bin/bash

X=6
while read line
do
    eval echo "$line" 
done < x

Output -

brad@TX5XN:~/wip$ y

D=aa.6.bb

brad@TX5XN:~/wip$

As you can see I lose the line with the #! from file x

If I redirect to a file -

brad@TX5XN:~/wip$ cat y
#! /bin/bash

X=6
while read line
do
    eval echo "$line"  > z
done < x

I lose all of the lines except the blank line from the end of the file -

brad@TX5XN:~/wip$ cat z

brad@TX5XN:~/wip$

Is there a simple and elegant way of doing this?

Thanks

Brad

The line #! /bin/bash is useless no matter how you cut it, for the space in it prevents it from working.

Try a here-document:

cat <<EOF
#!/bin/bash
D=aa.$X.bb
EOF

Of course, if you're templating hundreds of slightly different scripts/files, there is probably a more straightforward way to do what you want.

You could use awk (nawk or gawk).

This example looks for %%var%% and expands with the value of the shell variable. Note you need to export the variable so awk can see it:

expand.sh:

awk -F% ' /%%/ {
 while(match($0, "%%[A-Za-z0-9_]+%%")) {
    tmp = substr($0, 1, RSTART-1)
    var = substr($0, RSTART+2, RLENGTH-4);
    printf "%s%s", tmp, ENVIRON[var];
    $0=substr($0,RSTART+RLENGTH);
 }
 print; next } 1' $@

template:

dbname: %%DBNAME%%
dbusername:  %%DB_USER_NAME%%
dbpwd:  %%DB_PWD%%

Test script:

DBNAME="testing1"; export DBNAME
DB_USER_NAME="Test user"; export DB_USER_NAME
DB_PWD="/home/testing1"; export DB_PWD
./expand.sh template

guys thanks for the replies.

offline right now but will try these out tomorrow. :slight_smile:

eval takes the result of its parameters and starts expanding/executing it anew as if given from stdin. The # in #! /bin/bash makes this a comment line, so eval does not execute anything which results in the empty line that you see in your output.
Regarding your redirection: it does exactly what you told it to do: reset z to zero and overwrite it. Using >> z will append your output to z.

doh!

of course.

thanks :slight_smile: