Variable

將變數傳遞給 cat

  • May 31, 2019

我在 bash 腳本中只有一個變數,${PHP_V}並嘗試傳入 nginx 配置文件,例如:

cat <<'EOF' > /etc/nginx/sites-available/default
server {
   listen 80 default_server; 
   listen [::]:80 default_server; 

   listen 443 ssl default_server; 
   listen [::]:443 ssl default_server; 

   root /vagrant/webroot; 

   index index.php; 

   server_name _; 

   ssl_certificate /etc/nginx/certs/vagrantbox.crt; 
   ssl_certificate_key /etc/nginx/certs/vagrantbox.key;  

   location / { 
       try_files $uri $uri/ /index.php?$args; 
   } 

   location ~ \.php$ { 
       try_files $uri =404; 
       include fastcgi_params; 
       fastcgi_pass unix:/run/php/php${PHP_V}-fpm.sock; 
       fastcgi_index index.php; 
       fastcgi_intercept_errors on; 
       fastcgi_param SCRIPT_FILENAME 
       $document_root$fastcgi_script_name; 
   }
}
EOF

但沒有成功。怎麼做?

您需要取消報價EOF

如果 word 的任何部分被引用,則應通過對 word 進行引號去除來形成分隔符,並且不應擴展 here-document 行。否則,分隔符應為單詞本身。

如果沒有引用單詞的任何部分,則應擴展 here-document 的所有行以進行參數擴展、命令替換和算術擴展。

請參閱:2.7.4 Here-Document


但是請注意,您的此處文件中有幾件事需要單獨轉義以防止擴展:

cat <<EOF > /etc/nginx/sites-available/default
server {
   listen 80 default_server; 
   listen [::]:80 default_server; 

   listen 443 ssl default_server; 
   listen [::]:443 ssl default_server; 

   root /vagrant/webroot; 

   index index.php; 

   server_name _; 

   ssl_certificate /etc/nginx/certs/vagrantbox.crt; 
   ssl_certificate_key /etc/nginx/certs/vagrantbox.key;  

   location / { 
       try_files \$uri \$uri/ /index.php?\$args; 
   } 

   location ~ \.php\$ { 
       try_files \$uri =404; 
       include fastcgi_params; 
       fastcgi_pass unix:/run/php/php${PHP_V}-fpm.sock; 
       fastcgi_index index.php; 
       fastcgi_intercept_errors on; 
       fastcgi_param SCRIPT_FILENAME 
       \$document_root\$fastcgi_script_name; 
   }
}
EOF

引用自:https://unix.stackexchange.com/questions/522183