[英]Pass variable from shell script to config file
我必須編寫一個shell腳本來動態安裝多個服務。 我不太了解 shell 腳本或 unix shell 一般,所以我真的需要一些幫助。 這是我的shell文件。
#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname
echo You passed the domain name to your domain $varname successfully
這是我的 nginx.conf 文件。
server {
listen 80;
server_name $varname;
rewrite ^(.*) https://$server_name$1 permanent;
}
我想將varname
傳遞給 nginx.conf 文件以根據用戶輸入設置服務器名稱。 我怎樣才能做到這一點?
你能不能試試以下。 這將從空間開始並將server_name
的最后一個字段更改為用戶提供的值。
#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname
awk -v var="$varname" '/^ +server_name/{$NF=var} 1' nginx.conf > temp && mv temp nginx.conf &&\
echo You passed the domain name to your domain $varname successfully
您可以從 heredoc 創建文件nginx.conf
。
#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname
cat > nginx.conf <<EOF
server {
listen 80;
server_name $varname;
rewrite ^(.*) https://\$server_name\$1 permanent;
}
EOF
echo You passed the domain name to your domain $varname successfully
注意:在rewrite
行中,我轉義了$
字符以在輸出中獲得文字$
而不是 shell 變量擴展。
如果我輸入foobar
,這會產生一個像這樣的文件nginx.conf
:
server {
listen 80;
server_name foobar;
rewrite ^(.*) https://$server_name$1 permanent;
}
您可以為此使用envsubst
。
將您的nginx.conf
重命名為nginx.conf.template
並將您的腳本更改為:
#!/bin/bash
read -p "What is the name of your domain? " varname
export varname
envsubst '$varname' < nginx.conf.template > nginx.conf
echo "You passed the domain name to your domain $varname successfully"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.