Shell使用EOF写入文件时如何选择性处理或转义内部变量?
实现方案
方案1:使用无引号包裹的EOF,手动转义需保留的$符
当EOF标记不加单引号时,Shell会解析块内的所有变量,你只需要给不需要解析的$前缀加反斜杠\转义即可:
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
写入后文件内的\$uri会自动还原为$uri,而$port会被替换为对应的变量值。
方案2:保留单引号EOF,写入后单独替换端口
如果EOF块内有大量需要保留的$变量,不想逐个加转义符,可以保留原写法,写入完成后用sed替换端口行:
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 # 替换固定端口为动态变量值 sed -i "s/listen 3000;/listen $port;/" "${path}/nginx.conf" fi
这种方式不需要修改原有配置块内容,出错概率更低。
内容的提问来源于stack exchange,提问作者user3142695
相关产品推荐
相关产品推荐

