1

For my projects I need a way to generate some files based on template ones. I envision it this way:

  • a template file contains data with something like {{var1}} in place of the variables to be replaced

  • other file contains a list of key = value values

  • after applying a tool, a new file with concrete values should be generated

Instead of the 2nd file, a list of key = value pairs could be provided via the command line or, which is the same thing, some keys may require environmental variables instead of the keys-value in the 2nd file.

Are there standard and well known utilities used in Linux/Unix world that can do that?

6
0

It really is quite easy to script something like this. For instance, you can source the file with key=value pairs and then use that to replace the contents of the template. For example:

$ cat template
Hello $name,
someone told me you really like $thing!

$ cat values
name=Bob
thing=chocolate

Your script would then be:

#!/bin/sh

## source the key/value pairs
. "$1"

## Replace them in the template
sed -e "s/\\\$name/$name/g" -e "s/\\\$thing/$thing/g" "$2"

And you run it like this:

$ foo.sh /full/path/to/values template
Hello Bob,
someone told me you really like chocolate!

Of course, that requires you to know the names of the keys in advance. An alternative would be:

#!/bin/sh

tmpFile=$(mktemp)
cp -- "$2" "$tmpFile"

while IFS='=' read -r key value; do
  sed -i -e "s/\$$key/$value/g" "$tmpFile"
done < "$1"

cat "$tmpFile"

Another option would be to use eval to expand the variables. However, this is dangerous since it opens you up to code injection if the values in the file can be dangerous. If that's not an issue for you, try:

#!/bin/sh

## source the key/value pairs
. "$1"

## load the contents of the template
template="$(cat "$2")"
## Now print, but expanding the variables. We need to 
## unset IFS to protect the newlines.
IFS=
eval echo \"$template\"
3
  • You haven't completely understood my question.
    – kosmosu05
    Sep 27 '20 at 12:35
  • @kosmosu05 I assume you want something like a Makefile, but since I personally find that more trouble than it is worth (I find the syntax complex and arcane), I thought I would give you what IMO is a simpler and more readable approach using basic shell scripting.
    – terdon
    Sep 27 '20 at 12:42
  • No, I want something way more complicated, even more that what you've described
    – kosmosu05
    Sep 27 '20 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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