How I prepend a string on each item of an array?

Solution for How I prepend a string on each item of an array?
is Given Below:

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?

Edit 1

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.

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.

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