我正在编写一个脚本,为我自己的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/"
对我来说似乎很糟糕,因为需要转义许多不同的符号,而且有很多变量,这行代码太长了。
你能想出其他优雅而安全的解决方案吗?
发布于 2012-06-15 20:48:41
试试envsubst
FOO=foo
BAR=bar
export FOO BAR
envsubst <<EOF
FOO is $FOO
BAR is $BAR
EOF
发布于 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
发布于 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
https://stackoverflow.com/questions/2914220
复制相似问题