Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating string variable inside a for loop in the bash shell

Tags:

linux

bash

shell

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

@ndbd

I want to replace @ndbd with some other text to finalize 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 @ndbd with the generated substring.

However, my for loop doesn't seem to be concatenating all the data from $ip_ndbd, just 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'm getting:

[ndbd]
HostName=108.166.104.204 

I'm pretty sure there's a better way to write this, but I don't know how.

I'd appreciate some assistance.

Thanks in advance.

like image 512
ObiHill Avatar asked Mar 13 '12 21:03

ObiHill


2 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
like image 134
evil otto Avatar answered Oct 05 '22 21:10

evil otto


Replace

ip_ndbd=(108.166.104.204 108.166.105.47 108.166.56.241)

with

ip_ndbd="108.166.104.204 108.166.105.47 108.166.56.241"
like image 41
ebutusov Avatar answered Oct 05 '22 23:10

ebutusov