Reputation: 10028
I have the following bash script:
#!/bin/bash
items=('mysql_apache','postgresql_apache','maria_apache')
string=""
for i in "${array[@]}"; do
string=$string" -t"$i
done
echo $string
But if I output the string I won't get the expected result:
-t 'mysql_apache' -t 'postgresql_apache' -t 'maria_apache'
DO you have any Idea how I can do this?
I tried the following:
#!/bin/bash
items=('mysql_apache' 'postgresql_apache' 'maria_apache')
string=""
for i in "${array[@]}"; do
string=$string" -t"$i
done
echo $string
But I still do not get the expected output.
Upvotes: 1
Views: 616
Reputation: 41
You're close. Your forgot to change ${array[@]} in the for loop to what your array was named: items or specifically ${items[@]} You also needed a few other little changes, see below:
#!/bin/bash
declare -a items=('mysql_apache' 'postgresql_apache' 'maria_apache')
string=""
for i in "${items[@]}"; do
string=${string}" -t "$i
done
echo $string
Lastly if you want to see what is happening you can add temporary echo statements to see what if anything is changing:
for i in "${items[@]}"; do
string=${string}" -t "$i
echo >>>$string<<<
done
Upvotes: 1
Reputation: 241858
Array elements are separated by whitespace, not commas. Also, items
!= array
.
#! /bin/bash
items=(mysql_apache postgresql_apache maria_apache)
string=""
for i in "${items[@]}"; do
string+=" -t $i"
done
echo $string
But you don't need a loop at all:
items=(mysql_apache postgresql_apache maria_apache)
echo ${items[@]/#/-t }
The substitution can be applied to every element of an array. The /#
matches at the start of each string.
Upvotes: 4