Concatenating a string variable inside a for loop in a bash shell

I have a config.ini file with the following contents:

@ndbd

I want to replace @ndbdwith another text to complete the file. Below is my bash script code:

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

ip_temp=""
for ip in $ip_ndbd
do
    ip_temp+="\n\[ndbd\]\nHostname=$ip\n"   
done
perl -0777 -i -pe "s/\@ndbd/$ip_temp/" /var/lib/mysql-cluster/config.ini

Basically, I just want to get all the IP addresses in a specific format, and then replace it @ndbdwith the generated substring.

However, the my for loop does not combine all the data from $ip_ndbd, but only the first item in the list.

So, instead of getting:

[ndbd]
HostName=108.166.104.204 

[ndbd]
HostName=108.166.105.47 

[ndbd]
HostName=108.166.56.241

I get:

[ndbd]
HostName=108.166.104.204 

I am sure there is a better way to write this, but I do not know how to do this.

I would be grateful for the help.

Thanks in advance.

+5
source share
3 answers

If you want to iterate over an array variable, you need to specify the whole array:

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

ip_temp=""
for ip in ${ip_ndbd[*]}
do
    ip_temp+="\n\[ndbd\]\nHostname=$ip\n"   
done
+10

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

ip_ndbd="108.166.104.204 108.166.105.47 108.166.56.241"
+2

@ndbd...

, ?

kent$  echo "108.166.104.204 108.166.105.47 108.166.56.241"|awk '{for(i=1;i<=NF;i++){print "[ndbd]";print "HostName="$i;print ""}}'
[ndbd]
HostName=108.166.104.204

[ndbd]
HostName=108.166.105.47

[ndbd]
HostName=108.166.56.241

config.ini > config.ini

0

All Articles