In general, I would go for a search-and-replace approach using sed/awk such as that shown in Kent's answer or this answer.
If you want a shell-only approach, then the standard way would be to use eval
. However, this poses a security risk. For example:
[me@home]$ cat hello.txt
hello $NAME; uname -a
[me@home]$ NAME="shawn"
[me@home]$ eval echo "`cat hello.txt`" # DO NOT DO THIS!
hello shawn
Linux SOMEHOST 2.6.9-101.ELsmp #1 SMP Fri May 27 18:57:30 EDT 2011 i686 i686 i386 GNU/Linux
Notice how a command can be injected into the template!
You can however reduce the risk using this approach:
[me@home]$ eval "OUT=\"`cat hello.txt`\""
[me@home]$ echo $OUT
hello shawn; uname -a
Do note that this is still not foolproof as commands can still be injected using $(cmd)
or `cmd`
.
In short, you should use eval
only if you understand the risks and can control/limit access to the template files.
Here's an example of how this can be applied in your script:
function printout {
FILENAME=$1
eval "OUT=\"`cat $FILENAME`\""
echo $OUT
}
NAME=Joe
printout hello.txt
NAME=Nelly
printout hello.txt