首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Bash模板:如何使用Bash从模板构建配置文件?

Bash模板:如何使用Bash从模板构建配置文件?
EN

Stack Overflow用户
提问于 2010-05-26 23:12:17
回答 12查看 144K关注 0票数 158

我正在编写一个脚本,为我自己的and服务器自动创建Apache和PHP的配置文件。我不想使用任何像CPanel或ISPConfig这样的GUI。

我有一些Apache和PHP配置文件的模板。Bash脚本需要读取模板,进行变量替换,并将解析后的模板输出到某个文件夹中。做到这一点的最好方法是什么?我可以想出几种方法。哪一个是最好的,或者可能有更好的方法来做到这一点?我想用纯Bash来做这件事(举个例子,用PHP很容易)

1) How to replace ${} placeholders in a text file?

template.txt:

the number is ${i}
the word is ${word}

script.sh:

#!/bin/sh

#set variables
i=1
word="dog"
#read in template one line at the time, and replace variables
#(more natural (and efficient) way, thanks to Jonathan Leffler)
while read line
do
    eval echo "$line"
done < "./template.txt"

顺便说一下,我如何在这里将输出重定向到外部文件?如果变量包含引号,我需要转义吗?

2)使用cat & sed将每个变量替换为其值:

给定template.txt:

The number is ${i}
The word is ${word}

命令:

cat template.txt | sed -e "s/\${i}/1/" | sed -e "s/\${word}/dog/"

对我来说似乎很糟糕,因为需要转义许多不同的符号,而且有很多变量,这行代码太长了。

你能想出其他优雅而安全的解决方案吗?

EN

回答 12

Stack Overflow用户

发布于 2012-06-15 20:48:41

试试envsubst

FOO=foo
BAR=bar
export FOO BAR

envsubst <<EOF
FOO is $FOO
BAR is $BAR
EOF
票数 186
EN

Stack Overflow用户

发布于 2012-08-17 21:33:15

envsubst对我来说是新的。太棒了。

根据记录,使用heredoc是创建conf文件模板的一种很好的方法。

STATUS_URI="/hows-it-goin";  MONITOR_IP="10.10.2.15";

cat >/etc/apache2/conf.d/mod_status.conf <<EOF
<Location ${STATUS_URI}>
    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from ${MONITOR_IP}
</Location>
EOF
票数 64
EN

Stack Overflow用户

发布于 2010-05-27 02:13:53

我同意使用sed:它是搜索/替换的最佳工具。以下是我的方法:

$ cat template.txt
the number is ${i}
the dog's name is ${name}

$ cat replace.sed
s/${i}/5/
s/${name}/Fido/

$ sed -f replace.sed template.txt > out.txt

$ cat out.txt
the number is 5
the dog's name is Fido
票数 40
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2914220

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档