我正在编写一个脚本来自动为我自己的web服务器创建Apache和PHP的配置文件.我不想使用像CPanel或ISPConfig这样的任何GUI.
我有一些Apache和PHP配置文件的模板.Bash脚本需要读取模板,进行变量替换并将解析后的模板输出到某个文件夹中.最好的方法是什么?我可以想到几种方法.哪一个是最好的还是有更好的方法可以做到这一点?我想在纯Bash中做到这一点(例如在PHP中很容易)
template.txt:
the number is ${i}
the word is ${word}
Run Code Online (Sandbox Code Playgroud)
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"
Run Code Online (Sandbox Code Playgroud)
顺便说一句,如何在此处将输出重定向到外部文件?如果变量包含引号,我是否需要逃避某些事情?
2)使用cat&sed替换每个变量的值:
给出template.txt:
The number is ${i}
The word is ${word}
Run Code Online (Sandbox Code Playgroud)
命令:
cat template.txt | sed -e "s/\${i}/1/" | sed -e "s/\${word}/dog/"
Run Code Online (Sandbox Code Playgroud)
对我来说似乎不好,因为需要逃避许多不同的符号,并且对于许多变量,这条线太长了.
你能想到其他一些优雅而安全的解决方案吗?