【问题标题】:bash configuration templatingbash 配置模板
【发布时间】:2012-11-15 14:31:59
【问题描述】:

我正在使用 bash 脚本来安装和配置应用程序。我正在尝试使用一个模板,我可以在其中填写变量中的值,然后将其保存到适当的位置。这仅适用于变量,但我无法使用任何条件。有没有更好的方法来做到这一点?

这是我的示例模板:

    #!/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

然后我使用source template.sh &gt; /path/to/file 评估并保存文件。

【问题讨论】:

  • 想一想发生了什么,您是否希望执行cated 文件?这就是你做的对吗?除了cat 的文件源是由&lt;&lt;EOF here-document 提供的。那么为什么不按照你的source template &gt; filechmod 755 file; ./file 来执行里面的逻辑呢?

标签: bash templates scripting templating


【解决方案1】:

您不必将所有内容都包含在 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

【讨论】:

  • 我什至没有想过那样做...谢谢。
【解决方案2】:

你可以像这个简单的例子一样使用命令tpage

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

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

tpage 是众所周知的Perl 模块Template::Toolkit 附带的命令,但无需知道Perl 即可使用它。你也可以做一些有条件的,见conditional

项目:http://www.template-toolkit.org/

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2017-01-03
    • 2017-04-01
    • 1970-01-01
    相关资源
    最近更新 更多