1

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.

Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164

2 Answers2

4

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.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • 1
    BTW, this will misbehave with array elements that contain whitespace. If the command allows you to pass the option (`-t`) and its argument together (most commands allow this), you can use `somecommand "${items[@]/#/-t}"` (note the double-quotes and lack of space after `-t`). – Gordon Davisson Jul 30 '21 at 20:56
1

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
Craig D.
  • 41
  • 3
  • 1
    Embedding literal quotes in your data (as in `"'mysql_apache'"`) is almost always a mistake. It'll look right when `echo`ed, but won't actually work the way you might expect. See ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables) – Gordon Davisson Jul 30 '21 at 20:53
  • Great point Gordon, thank you. I've edited my answer to correct that. – Craig D. Jul 31 '21 at 22:15