Capt.Redbeard
Capt.Redbeard

Reputation: 790

bash configuration templating

I am using a bash script to install and configuration an application. I am trying to use a template where I can fill in values from variables and then save it to its proper location. This works fine with just variables, but I am unable to use any conditionals. Are there any better ways of doing this?

Heres my example template:

    #!/bin/bash

    cat <<EOF
    DEFAULTS: &DEFAULTS
      adapter: $DB
      host: $DB_HOST
      username: $DB_USER
      password: $DB_PASS
      database: $DB_DATABASE
      if [ ! $DB_RECONNECT = ""]; then
        reconnect: $DB_RECONNECT
      fi
      if [ ! $DB_TIMEOUT = ""]; then
        timeout: $DB_TIMEOUT  
      fi
    EOF

And then I use source template.sh > /path/to/file to evaluate and save the file.

Upvotes: 1

Views: 268

Answers (2)

doubleDown
doubleDown

Reputation: 8398

You don't have to enclose everything in the heredoc

cat <<EOF
...
database: $DB_DATABASE
EOF

if [ -z "$DB_RECONNECT" ]; then
    echo "reconnect: $DB_RECONNECT"
fi

if [ -z "$DB_TIMEOUT" ]; then
    echo "timeout: $DB_TIMEOUT"
fi

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185161

You can use the command tpage like in this simple example :

$ cat /tmp/l.tpl 
DEFAULTS: [%def%]
    adapter[%db%]

$ tpage --define def=foo --define db=bar --interpolate /tmp/l.tpl
DEFAULTS: foo
    adapterbar

tpage is a command coming with the well known Perl module Template::Toolkit, but no need to know Perl to use it. You can do some conditional as well, see conditional

Project : http://www.template-toolkit.org/

Upvotes: 0

Related Questions