我正在编写一个脚本来自动创建Apache和PHP的配置文件,用于我的Web服务器。我不想使用任何GUI,如CPanel或ISPConfig。
我有一些Apache和PHP配置文件的模板。Bash脚本需要读取模板,进行变量替换,并将解析后的模板输出到某个文件夹中。最好的方法是什么?我能想到几种方法。哪种是最好的,或者可能有更好的方法?我想在纯Bash中完成这个任务(例如,在PHP中很容易)
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"
顺便问一下,在这里如何将输出重定向到外部文件?如果变量包含引号,我需要转义什么吗?
- 使用cat和sed替换每个变量为其值:
给定template.txt(见上文)
命令:
cat template.txt | sed -e "s/\${i}/1/" | sed -e "s/\${word}/dog/"
我认为这样做不太好,因为需要转义很多不同的符号,而且如果有很多变量,那么这一行代码会非常长。
你能想到其他更优雅和安全的解决方案吗?