简体   繁体   中英

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:

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. 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. This is how printf is supposed to be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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