I read a string from a file with shell script variables, and want to substitute the variables with values in a function like
hello.txt:
-------------
Hello $NAME
a.sh
-------------
function printout
{
echo ???somehow_parse??? $1
}
NAME=Joe
printout "$(cat hello.txt)"
NAME=Nelly
printout "$(cat hello.txt)"
The example is not the best, but it describes my problem. In other words: can I use shell as a template engine?
I am using ksh.
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:Notice how a command can be injected into the template!
You can however reduce the risk using this approach:
Do note that this is still not foolproof as commands can still be injected using
$(cmd)or`cmd`.In short, you should use
evalonly 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: