envsubst 命令是 Linux 下的一个命令,常用与将变量传递到文件中,十分好用。

在没有了解到这个命令之前,我渲染配置时大多数会用sedecho来把环境变量中的值渲染到配置里。这种多个key的配置就得写多个sed有点 🤤🤤 的感觉。。。

使用样例

准备一个模板文件,例如文件名context.template (当然文件名是自定义的) 里面的NGINX_PORTNGINX_HOST 则是我们要渲染替换的值。

$ cat context.template
server {
    listen      ${NGINX_PORT};
    listen      [::]:${NGINX_PORT};
    server_name ${NGINX_HOST};

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}

准备key的值:

$ export NGINX_PORT='80'
$ export NGINX_HOST='baidu.com'

然后执行命令,进行渲染配置到context.conf文件中

$ envsubst  < context.template > context.conf

查看文件内容:

$ cat context.conf
server {
    listen      80;
    listen      [::]:80;
    server_name baidu.com;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }
}
最后修改:2024 年 01 月 06 日
如果觉得我的文章对你有用,请随意赞赏