简体   繁体   English

bash将多行插入到包含数组变量的文本文件中

[英]bash insert multiple lines into a text file including variables from an array

I want to insert multiple lines of text which include an array variable into a text file however it is printing the variable name instead of inserting the variable itself, my code is: 我想将包含数组变量的多行文本插入文本文件,但是它正在打印变量名而不是插入变量本身,我的代码是:

printf 'server {\n server_name ${cdarray[choice]} www.${cdarray[choice]};\n root /home/nginx/domains/cmmdm/suspendedpage;\n location / {\n try_files $uri $uri/ /index.html;\n }\n}'  >> /usr/local/nginx/conf/conf.d/${cdarray[choice]}.txt

IF the array variable contains 'demo-domain.com' the output should look like this: 如果数组变量包含“ demo-domain.com”,则输出应如下所示:

server {
server_name demo-domain.com www.demo-domain.com;
root /home/nginx/domains/cmmdm/suspendedpage;
location / {
try_files $uri $uri/ /index.html;
}
}

but its coming out as: 但它的出现是:

server {
server_name ${cdarray[choice]} www.${cdarray[choice]};
root /home/nginx/domains/cmmdm/suspendedpage;
location / {
try_files $uri $uri/ /index.html;
}
}

好的,轻松修复,将其从单引号更改为双引号解决了这个问题。

As you noticed, changing from single quotes to double quotes seems to solve the issue. 如您所见,将单引号更改为双引号似乎可以解决此问题。 Yet, this is not how printf is supposed to be used. 但是,这不是应该使用printf方式。 For example, if you have some percent % signs in your variables, you'll get weird results. 例如,如果你有一些百分之%中的变量标志,你会得到奇怪的结果。 Instead use this: 而是使用此:

printf 'server {\n server_name %s www.%s;\n root /home/nginx/domains/cmmdm/suspendedpage;\n location / {\n try_files %s %s/ /index.html;\n }\n}' "${cdarray[choice]}" "${cdarray[choice]}" "$uri" "$uri" >> "/usr/local/nginx/conf/conf.d/${cdarray[choice]}.txt"

Each %s will be replaced by the corresponding argument. 每个%s将被相应的参数替换。 This is how printf is supposed to be used. 这就是应该如何使用printf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM