ObiHill
ObiHill

Reputation: 11876

Concatenating string variable inside a for loop in the 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.

Upvotes: 5

Views: 20430

Answers (3)

evil otto
evil otto

Reputation: 10582

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

Upvotes: 12

ebutusov
ebutusov

Reputation: 573

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"

Upvotes: 2

Kent
Kent

Reputation: 195079

i didn't see any usage of your file with content @ndbd...

is this what you want?

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

you could just redirect the output to your config.ini file by > config.ini

Upvotes: 0

Related Questions