【问题标题】:How to process or excape variables inside of EOF to write file content?如何处理或 excape EOF 内的变量以写入文件内容?
【发布时间】:2021-10-08 13:33:12
【问题描述】:

这就是我通过 shell 创建文件 (nginx.conf) 的方式。 因为文件内容中有$ 字符,所以我使用EOF。

if [ $type == "nginx" ]; then
    cat > ${path}/nginx.conf <<'EOF'
server {
listen 3000;

location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
}

include /etc/nginx/extra-conf.d/*.conf;
}
EOF
fi

现在我必须使用动态端口值,所以我需要使用listen $port 而不是listen 3000。 但这行不通,因为内容中还有$uri,应该作为文本处理,而不是作为变量处理。

【问题讨论】:

    标签: shell nginx eof


    【解决方案1】:

    仅使用定界符本身,要么扩展所有参数,要么不扩展。您必须允许扩展,但要避开 $uri 的美元符号以抑制它们的扩展。

    if [ "$type" = "nginx" ]; then
        cat > "${path}/nginx.conf" <<EOF
    server {
    listen $port;
    
    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files \$uri \$uri/ /index.html = 404;
    }
    
    include /etc/nginx/extra-conf.d/*.conf;
    }
    EOF
    fi
    

    此处文档的行为类似于双引号字符串:

    $ foo=bar
    $ echo "$foo"
    bar
    $ echo "\$foo"
    $foo
    

    【讨论】:

    • 应该是listen $port还是listen ${port}?
    • 两者都可以。 ${port} 是编写参数扩展的规范方式,但可以省略大括号,因为您没有使用任何扩展运算符,并且 ; 不能被视为参数名称的一部分。
    • (别问我当初为什么把状态码换成$port而不是端口号,现在已经修好了。)
    猜你喜欢
    • 2011-03-05
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    • 2022-10-08
    相关资源
    最近更新 更多