代码之家  ›  专栏  ›  技术社区  ›  user3142695

如何处理或提取EOF中的变量以写入文件内容?

  •  0
  • user3142695  · 技术社区  · 4 年前

    这就是我创建文件的方式( 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 3000 我需要使用 listen $port . 但这是行不通的,因为在内容上也有 $uri ,应该作为文本处理,而不是作为变量处理。

    1 回复  |  直到 4 年前
        1
  •  1
  •   chepner    4 年前

    仅使用分隔符本身,可以展开所有参数,也可以不展开任何参数。你必须允许扩张,但要避开美元的迹象 $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