添加站点到 Varnish 时如何避免重复 sed 命令?

添加站点到 Varnish 时如何避免重复 sed 命令?

这是我安装 Varnish 的脚本。每次我在 VPS 上建立新的服务器环境时都会运行它。

cd ~
apt-get update
apt-get install varnish -y
sed -i 's/Listen 80/Listen 8080/g' /etc/apache2/ports.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/000-default.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain1.tld.conf && a2ensite domain1.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain2.tld.conf && a2ensite domain2.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain3.tld.conf && a2ensite domain3.tld.conf
sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/domain4.tld.conf && a2ensite domain4.tld.conf
mkdir -p /etc/systemd/system/varnish.service.d # Be aware! You might not need this in the future.
cat <<-'VARNISH' > /etc/systemd/system/varnish.service.d/customexec.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
VARNISH
systemctl restart apache2.service && systemctl daemon-reload && systemctl restart varnish.service

这段代码看起来相当“重”,尤其是关于domain.tld的sed操作的重复性。

这甚至变得“更重”,因为我有一个长度相似的代码段,用于我卸载清漆并在需要时恢复所有更改。

我的问题:

您将采取什么策略来使安装脚本总体上更短(至少更少的行,也可能更少的命令),特别是减少 sed 操作的数量。

笔记:

  • 我假设要做的第一件事是以某种方式将 ports.conf、000-default.conf 和每个站点的每个 .conf 文件统一为一个操作。也许通过 for 循环/etc/apache2/ports.conf/ && /etc/apache2/sites-available/*/

答案1

使用函数和 GNU Parallel 替换重复部分:

cd ~
apt-get update
apt-get install varnish -y
sed -i 's/Listen 80/Listen 8080/g' /etc/apache2/ports.conf

myfunc() {
    sed -i 's/\*\:80/\*\:8080/g' /etc/apache2/sites-available/$1 && 
      a2ensite $1
}
export -f myfunc

parallel myfunc  {/} ::: /etc/apache2/sites-available/*

mkdir -p /etc/systemd/system/varnish.service.d # Be aware! You might not need this in the future.
cat <<-'VARNISH' > /etc/systemd/system/varnish.service.d/customexec.conf
[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m
VARNISH
systemctl restart apache2.service && systemctl daemon-reload && systemctl restart varnish.service

相关内容