如何使用 bash 从模板生成文件脚本?
我正在尝试为我们的内部开发服务器自动设置站点创建。
目前,这包括创建系统用户、mysql 用户、数据库和 apache 配置。我知道如何在一个 bash 文件中完成所有操作,但我想问是否有一种方法可以更干净地生成 apache 配置。
本质上我想做的是基于模板生成一个conf文件,类似于使用printf。我当然可以使用 printf,但我认为可能有一种更简洁的方法,使用 sed 或 awk。
我不只是想使用 printf 的原因是因为 apache 配置大约有 20 行长,并且会占用大部分 bash 脚本,并且使其更难以阅读。
任何帮助表示赞赏。
I am trying to automate the set up of site creation for our in-house development server.
Currently, this consists of creating a system user, mysql user, database, and apache config. I know how I can do everything in a single bash file, but I wanted to ask if there was a way to more cleanly generate the apache config.
Essentially what I want to do is generate a conf file based on a template, similar to using printf. I could certainly use printf, but I thought there might be a cleaner way, using sed or awk.
The reason I don't just want to use printf is because the apache config is about 20 lines long, and will take up most of the bash script, as well as make it harder to read.
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
选择标记参数的方式。一种可能是
:parameter:
,但是任何不会与模板文件的合法文本混淆的类似标记对都是好的。编写一个
sed
脚本(使用sed
、awk
、perl
...),类似于以下内容:当您有时需要编辑某些内容有时不需要时,您可能会发现在命令文件中创建相关的 sed 命令然后执行该命令会更容易:
请注意,您应该使用确保临时对象不会失去其用处的陷阱:
这可以确保您的当脚本针对大多数合理信号退出时,临时文件将被删除。您可以保留之前命令的非零退出状态,并在
trap 0
命令后使用exit $exit_status
。Choose a way of marking parameters. One possibility is
:parameter:
, but any similar pair of markers that won't be confused with legitimate text for the template file(s) is good.Write a
sed
script (insed
,awk
,perl
, ...) similar to the following:If you get to a point where you need sometimes to edit something and sometimes don't, you may find it easier to create the relevant
sed
commands in a command file and then execute that:Note that you should use a trap to ensure the temporary doesn't outlive its usefulness:
This ensures that your temporary file is removed when the script exits for most plausible signals. You can preserve a non-zero exit status from previous commands and use
exit $exit_status
after thetrap 0
command.我很惊讶没有人提到这里的文件。这可能不是OP想要的,但肯定是提高您开始使用的脚本的可读性的一种方法。只需注意转义或参数化 shell 将对其执行替换的任何构造即可。
在这种情况下,为了清晰起见并避免任何可能的歧义,我建议使用 ${variable} 而不是等效的 $variable。
I'm surprised nobody mentioned here documents. This is probably not what the OP wants, but certainly a way to improve legibility of the script you started out with. Just take care to escape or parametrize away any constructs which the shell will perform substitutions on.
In this context I would recommend ${variable} over the equivalent $variable for clarity and to avoid any possible ambiguity.
例如使用 sed
Use sed like for example